Fastify MCP Server
A Fastify plugin that implements the Model Context Protocol (MCP) server using JSON-RPC 2.0. This plugin enables Fastify applications to expose tools, resources, and prompts following the MCP 2025-06-18 specification with full elicitation support.
Installation
bashnpm install @platformatic/mcp
TypeBox Support (Optional)
For type-safe schema validation, install TypeBox:
bashnpm install @sinclair/typebox
Features
- Complete MCP 2025-11-25 Support: Implements the current Model Context Protocol revision, negotiating down to
2025-06-18,2025-03-26and2024-11-05for older clients - Tasks (experimental): Task-augmented tool calls with polling, deferred result retrieval and cancellation
- Elicitation Support: Server-to-client information requests in both form and URL mode, with schema validation
- Icons: Optional icon metadata on tools, resources, resource templates and prompts
- TypeBox Validation: Type-safe schema validation with automatic TypeScript inference
- Security Enhancements: Input sanitization, rate limiting, and security assessment
- Multiple Transport Support: HTTP/SSE and stdio transports for flexible communication
- SSE Streaming: Server-Sent Events for real-time communication
- Horizontal Scaling: Redis-backed session management and message broadcasting
- Session Persistence: Message history and reconnection support with Last-Event-ID
- Memory & Redis Backends: Seamless switching between local and distributed storage
- Production Ready: Comprehensive test coverage, security features, and authentication support
Quick Start
typescriptimport Fastify from 'fastify' import mcpPlugin from '@platformatic/mcp' // Or use named import: // import { mcpPlugin } from '@platformatic/mcp' const app = Fastify({ logger: true }) // Register the MCP plugin await app.register(mcpPlugin, { serverInfo: { name: 'my-mcp-server', version: '1.0.0' }, capabilities: { tools: { listChanged: true }, resources: { subscribe: true }, prompts: {} }, instructions: 'This server provides custom tools and resources' }) // Add tools, resources, and prompts with handlers app.mcpAddTool({ name: 'calculator', description: 'Performs basic arithmetic operations', inputSchema: { type: 'object', properties: { operation: { type: 'string', enum: ['add', 'subtract', 'multiply', 'divide'] }, a: { type: 'number' }, b: { type: 'number' } }, required: ['operation', 'a', 'b'] } }, async (params) => { const { operation, a, b } = params let result switch (operation) { case 'add': result = a + b; break case 'subtract': result = a - b; break case 'multiply': result = a * b; break case 'divide': result = a / b; break default: throw new Error('Invalid operation') } return { content: [{ type: 'text', text: `Result: ${result}` }] } }) app.mcpAddResource({ uri: 'file://config.json', name: 'Application Config', description: 'Server configuration file', mimeType: 'application/json' }, async (uri, context) => { // Read and return the configuration file const config = { setting1: 'value1', setting2: 'value2' } return { contents: [{ uri, text: JSON.stringify(config, null, 2), mimeType: 'application/json' }] } }) app.mcpAddPrompt({ name: 'code-review', description: 'Generates code review comments', arguments: [{ name: 'language', description: 'Programming language', required: true }] }, async (name, args, context) => { const language = args?.language || 'javascript' return { messages: [{ role: 'user', content: { type: 'text', text: `Please review this ${language} code for best practices, potential bugs, and improvements.` } }] } }) await app.listen({ port: 3000 })
In-process MCP Client
The plugin decorates the Fastify instance with mcpClient(), a client that talks to the
server through app.inject() — no port binding, so it's equally useful for tests or for
driving the server from other in-process code:
typescriptimport { test } from 'node:test' import assert from 'node:assert/strict' import Fastify from 'fastify' import type { FastifyInstance } from 'fastify' import mcpPlugin from '@platformatic/mcp' test('calls an MCP tool', async (t) => { const app: FastifyInstance = Fastify() t.after(() => app.close()) await app.register(mcpPlugin, { enableSSE: true }) app.mcpAddTool({ name: 'echo', description: 'Echo a message', inputSchema: { type: 'object', properties: { message: { type: 'string' } }, required: ['message'], additionalProperties: false } }, async ({ message }) => { return { content: [{ type: 'text', text: message }] } }) await app.ready() const client = app.mcpClient() await client.initialize() const response = await client.callTool('echo', { message: 'hello' }) assert.equal(response.statusCode, 200) assert.ok('result' in response.body) assert.deepEqual(response.body.result, { content: [{ type: 'text', text: 'hello' }] }) })
The client:
- Uses
app.inject()only (no port binding). - Manages sequential JSON-RPC request IDs per client instance.
initialize()performs the complete MCP lifecycle handshake (initializeplusnotifications/initialized).initialize()rejects whennotifications/initializedis not accepted with an empty202or204response.- Commits
mcp-session-idand negotiated protocol version only after the full initialization handshake succeeds. - Forwards headers passed to
initialize()to both lifecycle requests, except MCP-managedmcp-session-idandmcp-protocol-versiononnotifications/initialized. - Captures committed
mcp-session-idfrom successful initialization and sends it automatically on later requests. - Lets you pass custom headers (including authorization) globally or per request.
Responses are a discriminated union — narrow with 'result' in response.body or
'error' in response.body. Malformed or non-JSON-RPC responses throw a coded Fastify error
instead of returning.
Note: no OAuth/JWT credentials are generated for you.
Protocol Version Negotiation
The server answers initialize with the client's requested revision when it is one it
supports, and otherwise offers the newest one it has:
typescriptimport { LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS } from '@platformatic/mcp' LATEST_PROTOCOL_VERSION // '2025-11-25' SUPPORTED_PROTOCOL_VERSIONS // ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05']
On the HTTP transport, requests after initialize must carry the agreed revision in the
MCP-Protocol-Version header. An unsupported value is answered with 400; an absent header
is treated as 2025-03-26, which predates the header.
Responses are shaped to the revision the client negotiated. A client on an older revision never sees a field or method that revision does not define:
< 2025-11-25 | 2025-11-25 | |
|---|---|---|
tasks capability | not advertised | advertised |
tasks/* methods | -32601 method not found | available |
task field on tools/call | ignored | honoured |
icons on listings | stripped | present |
execution.taskSupport | stripped | present |
$schema on tool schemas | omitted | JSON Schema 2020-12 |
| URL mode elicitation | refused | available |
When SSE is enabled the negotiated revision is stored on the session and is authoritative:
a request whose MCP-Protocol-Version header contradicts what the session agreed is rejected
with 400, so a client cannot opt into newer behaviour after negotiating an older revision.
When the header is omitted the session's revision is used in preference to the 2025-03-26
default. initialize is exempt, so a client may re-negotiate on an existing session.
Without SSE there is no session to remember the negotiation, so each request is judged solely by its header. A client that omits it falls back to
2025-03-26and will not see2025-11-25features. Compliant clients always send the header.
Origin Validation
Browser clients can be protected against DNS rebinding by allow-listing origins. A rejected
origin is answered with 403:
typescriptawait app.register(mcpPlugin, { allowedOrigins: ['https://app.example.com'] // omit to disable, '*' or true to allow any })
Requests without an Origin header are always accepted — the header is set by browsers, so
its absence means the request did not come from one.
Tasks (MCP 2025-11-25, experimental)
Tasks let a tool call return immediately with a task handle while the work continues in the
background. The client then polls tasks/get and collects the result with tasks/result.
Enable the feature on the plugin, then opt individual tools in with execution.taskSupport:
typescriptawait app.register(mcpPlugin, { enableTasks: true }) app.mcpAddTool({ name: 'generate-report', description: 'Builds a large report', inputSchema: Type.Object({ month: Type.String() }), execution: { taskSupport: 'optional' } // 'forbidden' (default) | 'optional' | 'required' }, async (params) => { return { content: [{ type: 'text', text: await buildReport(params.month) }] } })
A client opts in per call by adding a task field:
jsonc// -> tools/call { "name": "generate-report", "arguments": { "month": "July" }, "task": { "ttl": 60000 } } // <- CreateTaskResult { "task": { "taskId": "…", "status": "working", "ttl": 60000, "pollInterval": 1000 } }
Supported operations: tasks/get, tasks/result (blocks until the task is terminal),
tasks/list and tasks/cancel, plus optional notifications/tasks/status pushes over SSE.
Retention defaults to 60 seconds when the client does not request a ttl. Tasks are meant
for long-running work, so if your tools can outlive that, raise the bounds — otherwise a task
can expire before it finishes and its tasks/result returns "not found":
typescriptawait app.register(mcpPlugin, { enableTasks: true, taskDefaultTtlMs: 15 * 60_000, // retention when the client requests no ttl taskMaxTtlMs: 60 * 60_000 // ceiling on a client-requested ttl })
Tasks are stored in memory by default and in Redis when a redis option is given, so any
instance can serve a poll for a task created on another.
Security: when authorization is enabled, tasks are bound to the token subject and a
requestor can only reach its own. Without authorization no requestor can be identified, so
tasks are reachable by anyone holding the (random UUID) task id, and tasks/list is both
unadvertised and refused — otherwise it would hand every anonymous task's id to any
caller and defeat that model.
Elicitation Support (MCP 2025-11-25)
The plugin supports the elicitation capability, allowing servers to request structured information from clients. This enables dynamic data collection with schema validation.
Two modes are available. Form mode collects structured data through the client, and URL mode sends the user out of band for anything sensitive — credentials, payments, third-party OAuth — so it never passes through the MCP client:
typescript// URL mode: returns the elicitation id, or null if the request could not be sent const elicitationId = await app.mcpElicitUrl( sessionId, 'Authorize access to your Example Co files', 'https://mcp.example.com/connect' ) // Later, once the out-of-band interaction finishes await app.mcpNotifyElicitationComplete(sessionId, elicitationId)
Servers MUST NOT request passwords, API keys or payment details through form mode — use URL mode for those. URLs are rejected if they are malformed, use a scheme other than http(s), or embed credentials.
Basic Elicitation
typescriptimport { Type } from '@sinclair/typebox' // Register plugin with elicitation support await app.register(mcpPlugin, { enableSSE: true, // Required for elicitation capabilities: { elicitation: {} // Enable elicitation capability } }) // In your tool handler, request information from the client app.mcpAddTool({ name: 'collect-user-info', description: 'Collect user information', inputSchema: Type.Object({}) }, async (params, { sessionId }) => { if (!sessionId) { return { content: [{ type: 'text', text: 'No session available' }], isError: true } } // Request user details with schema validation const success = await app.mcpElicit(sessionId, 'Please enter your details', { type: 'object', properties: { name: { type: 'string', description: 'Your full name', minLength: 1, maxLength: 100 }, email: { type: 'string', description: 'Your email address', format: 'email' }, age: { type: 'integer', description: 'Your age', minimum: 0, maximum: 150 }, preferences: { type: 'array', items: { type: 'string', enum: ['newsletter', 'updates', 'marketing'] }, description: 'Communication preferences' } }, required: ['name', 'email'] }) if (success) { return { content: [{ type: 'text', text: 'Information request sent to client' }] } } else { return { content: [{ type: 'text', text: 'Failed to send elicitation request' }], isError: true } } })
Advanced Elicitation with Custom Request IDs
typescript// Request with custom ID for tracking const requestId = 'user-profile-123' const success = await app.mcpElicit( sessionId, 'Complete your profile setup', { type: 'object', properties: { avatar: { type: 'string', description: 'Avatar URL' }, bio: { type: 'string', maxLength: 500, description: 'Short bio' }, skills: { type: 'array', items: { type: 'string' }, maxItems: 10, description: 'Your skills' } } }, requestId )
Security Considerations for Elicitation
⚠️ Important Security Notes:
- Elicitation requests are automatically validated for length and complexity
- Schema depth and size are limited to prevent DoS attacks
- Rate limiting should be implemented for production use
- Always validate client responses before using the data
- Never request sensitive information without explicit user consent
TypeBox Schema Validation
The plugin supports TypeBox schemas for type-safe validation with automatic TypeScript inference. This eliminates the need for manual type definitions and provides compile-time type checking.
Benefits
- Type Safety: Automatic TypeScript type inference from schemas
- Runtime Validation: Input validation with structured error messages
- Zero Duplication: Single source of truth for both types and validation
- IDE Support: Full autocomplete and IntelliSense for validated parameters
- Performance: Compiled validators with caching for optimal performance
Basic Usage
typescriptimport { Type } from '@sinclair/typebox' import Fastify from 'fastify' import mcpPlugin from '@platformatic/mcp' const app = Fastify({ logger: true }) await app.register(mcpPlugin, { serverInfo: { name: 'my-server', version: '1.0.0' }, capabilities: { tools: {} } }) // Define TypeBox schema const SearchToolSchema = Type.Object({ query: Type.String({ minLength: 1, description: 'Search query' }), limit: Type.Optional(Type.Number({ minimum: 1, maximum: 100, description: 'Maximum results' })), filters: Type.Optional(Type.Array(Type.String(), { description: 'Filter criteria' })) }) // Register tool with TypeBox schema app.mcpAddTool({ name: 'search', description: 'Search for files', inputSchema: SearchToolSchema }, async (params) => { // params is automatically typed as: // { // query: string; // limit?: number; // filters?: string[]; // } const { query, limit = 10, filters = [] } = params return { content: [{ type: 'text', text: `Searching for "${query}" with limit ${limit} and filters: ${filters.join(', ')}` }] } })
Schema Types
Tool Input Schemas
typescript// Complex nested schema const ComplexToolSchema = Type.Object({ user: Type.Object({ name: Type.String(), age: Type.Number({ minimum: 0 }) }), preferences: Type.Object({ theme: Type.Union([ Type.Literal('light'), Type.Literal('dark'), Type.Literal('auto') ]), notifications: Type.Boolean() }), tags: Type.Array(Type.String()) }) app.mcpAddTool({ name: 'update-profile', description: 'Update user profile', inputSchema: ComplexToolSchema }, async (params) => { // Fully typed nested object const { user, preferences, tags } = params return { content: [{ type: 'text', text: `Updated profile for ${user.name}` }] } })
Resource URI Schemas
typescript// URI validation schema const FileUriSchema = Type.String({ pattern: '^file://.+', description: 'File URI pattern' }) app.mcpAddResource({ uriPattern: 'file://documents/*', name: 'Document Files', description: 'Access document files', uriSchema: FileUriSchema }, async (uri, context) => { // uri is validated against the schema const content = await readFile(uri) return { contents: [{ uri, text: content, mimeType: 'text/plain' }] } })
Prompt Argument Schemas
typescript// Prompt with automatic argument generation const CodeReviewSchema = Type.Object({ language: Type.Union([ Type.Literal('javascript'), Type.Literal('typescript'), Type.Literal('python') ], { description: 'Programming language' }), complexity: Type.Optional(Type.Union([ Type.Literal('low'), Type.Literal('medium'), Type.Literal('high') ], { description: 'Code complexity level' })) }) app.mcpAddPrompt({ name: 'code-review', description: 'Generate code review', argumentSchema: CodeReviewSchema // arguments array is automatically generated from schema }, async (name, args, context) => { // args is typed as: { language: 'javascript' | 'typescript' | 'python', complexity?: 'low' | 'medium' | 'high' } return { messages: [{ role: 'user', content: { type: 'text', text: `Review this ${args.language} code with ${args.complexity || 'medium'} complexity` } }] } })
Error Handling
TypeBox validation provides structured error messages:
typescript// When validation fails, structured errors are returned: { "jsonrpc": "2.0", "id": 1, "result": { "isError": true, "content": [{ "type": "text", "text": "Invalid tool arguments: Validation failed with 2 errors:\n/query: Expected string, received number\n/limit: Expected number <= 100, received 150" }] } }
Backward Compatibility
The plugin maintains backward compatibility with JSON Schema and unvalidated tools:
typescript// JSON Schema (accepted, but NOT validated at runtime by default — see below) app.mcpAddTool({ name: 'legacy-tool', description: 'Uses JSON Schema', inputSchema: { type: 'object', properties: { param: { type: 'string' } } } }, async (params) => { // params is typed as 'any' return { content: [{ type: 'text', text: 'OK' }] } }) // Unvalidated tool (unsafe) app.mcpAddTool({ name: 'unsafe-tool', description: 'No validation' }, async (params) => { // params is typed as 'any' - no validation performed return { content: [{ type: 'text', text: 'OK' }] } })
Important: only TypeBox schemas are validated at runtime by default. A tool registered with a plain JSON Schema inputSchema receives its arguments unvalidated unless you opt in to AJV validation.
Validating plain JSON Schema inputs with AJV
Set validateJsonSchemaInputs: {} to validate plain-JSON-Schema tool inputs with AJV (draft 2020-12, matching the plugin's published schema dialect) before the handler runs. TypeBox tools are unaffected — they keep their existing TypeBox validation.
typescriptawait app.register(mcpPlugin, { validateJsonSchemaInputs: { allErrors: true, useDefaults: false } })
Behavior when enabled:
- Invalid arguments return a tool execution error (
isError: truewith anInvalid tool arguments: ...message, capped at 5 reported errors), not a protocol error — the same SEP-1303 semantics as TypeBox validation. - Validation is non-mutating: no type coercion, no defaults injection, no property removal. Handlers receive the arguments exactly as the client sent them.
formatkeywords are annotation-only (JSON Schema 2020-12's own default). - A plain JSON Schema that AJV cannot compile makes
mcpAddToolthrow, so a misconfigured tool fails at startup instead of running unvalidated. - Compiled validators are cached per schema, and the option also applies to stdio transports and task-augmented (
task: {}) calls.
Performance
TypeBox validation is highly optimized:
- Compiled Validators: Schemas are compiled to optimized validation functions
- Caching: Compiled validators are cached for reuse
- Minimal Overhead: Less than 1ms validation overhead for typical schemas
- Memory Efficient: Shared validator instances across requests
Server-Sent Events (SSE) Support
This plugin supports the MCP Streamable HTTP transport specification, enabling both regular JSON responses and Server-Sent Events for streaming communication.
SSE Configuration
typescriptawait app.register(mcpPlugin, { enableSSE: true, // Enable SSE support (default: false) // Optionally close streams after a while so clients fall back to polling and // resume with Last-Event-ID (SEP-1699). Omit to keep streams open indefinitely. sseMaxConnectionMs: 300_000, // ... other options })
Redis Configuration for Horizontal Scaling
The plugin supports Redis-backed session management and message broadcasting for horizontal scaling across multiple server instances.
Why Redis is Critical for Scalability
Without Redis (Memory-only):
- Each server instance maintains isolated session stores
- SSE connections are tied to specific server instances
- No cross-instance message broadcasting
- Session data is lost when servers restart
- Load balancers can't route clients to different instances
With Redis (Distributed):
- Shared Session State: All instances access the same session data from Redis
- Cross-Instance Broadcasting: Messages sent from any instance reach all connected clients
- Session Persistence: Sessions survive server restarts with 1-hour TTL
- High Availability: Clients can reconnect to any instance and resume from last event
- True Horizontal Scaling: Add more instances without architectural changes
This transforms the plugin from a single-instance application into a distributed system capable of serving thousands of concurrent SSE connections with real-time global synchronization.
Redis Setup
typescriptimport Fastify from 'fastify' import mcpPlugin from '@platformatic/mcp' const app = Fastify({ logger: true }) await app.register(mcpPlugin, { enableSSE: true, redis: { host: process.env.REDIS_HOST || 'localhost', port: parseInt(process.env.REDIS_PORT || '6379'), db: parseInt(process.env.REDIS_DB || '0'), password: process.env.REDIS_PASSWORD, // Additional ioredis options retryDelayOnFailover: 100, maxRetriesPerRequest: 3 }, serverInfo: { name: 'scalable-mcp-server', version: '1.0.0' } })
Message Broker Exports
MemoryMessageBroker, RedisMessageBroker, and the MessageBroker interface are exported from the package's public entry point, so you can use them directly without deep-importing into dist/brokers/...:
typescriptimport { MessageBroker, MemoryMessageBroker, RedisMessageBroker } from '@platformatic/mcp' const broker: MessageBroker = new MemoryMessageBroker() // or: new RedisMessageBroker(redis)
MessageBroker: the pub/sub interface the plugin uses internally to deliver messages to SSE clients —publish(topic, message),subscribe(topic, handler),unsubscribe(topic), andclose().MemoryMessageBroker: in-process implementation backed by MQEmitter. Used automatically when noredisoption is passed; messages only reach clients connected to the same server instance.RedisMessageBroker: distributed implementation backed by mqemitter-redis. Used automatically when theredisoption is passed; publishes go through Redis so messages reach clients connected to any server instance.
These are the same broker classes the plugin instantiates internally based on the redis option. Exporting them lets you construct one directly for custom pub/sub logic, tests, or scripts that need to publish/subscribe without spinning up the full plugin.
Session Store Exports
MemorySessionStore, RedisSessionStore, and the SessionStore/SessionMetadata types are exported from the package's public entry point, matching the broker and task store exports:
typescriptimport { SessionStore, MemorySessionStore, RedisSessionStore } from '@platformatic/mcp' const store: SessionStore = new MemorySessionStore() // or: new RedisSessionStore({ redis })
SessionStore: the interface the plugin uses to persist SSE session metadata, message history, and token-to-session mappings.MemorySessionStore: in-process implementation used automatically when noredisoption is passed. Takes an optionalmaxMessageshistory cap (default 100).RedisSessionStore: distributed implementation used automatically when theredisoption is passed; sessions and message history live in Redis so any instance can serve any client.
These are the same store classes the plugin instantiates internally based on the redis option. Exporting them lets you construct or inspect one directly in tests and scripts.
Multi-Instance Deployment
With Redis configuration, you can run multiple instances of your MCP server:
bash# Instance 1 PORT=3000 REDIS_HOST=redis.example.com node server.js # Instance 2 PORT=3001 REDIS_HOST=redis.example.com node server.js # Instance 3 PORT=3002 REDIS_HOST=redis.example.com node server.js
Graceful Shutdown
RedisMessageBroker.close() is bounded: it waits up to closeTimeoutMs (default 2000ms) for
mqemitter-redis to close its Redis connections gracefully, then falls back to forcibly
disconnecting them so Fastify's onClose hooks - and the process shutdown deadline enforced by
most orchestrators - are never blocked by a Redis outage or a stuck reconnect. Pass
closeTimeoutMs and onCloseTimeout as a second argument to RedisMessageBroker to customize
this behavior, e.g. to log when a shutdown had to fall back to the forced path.
Session Persistence Features
Automatic Session Management:
- Sessions persist across server restarts
- 1-hour session TTL with automatic cleanup
- Message history stored in Redis Streams
Message Replay:
javascript// Client reconnection with Last-Event-ID const eventSource = new EventSource('/mcp', { headers: { 'Accept': 'text/event-stream', 'Last-Event-ID': '1234' // Resume from this event } })
Cross-Instance Broadcasting:
typescript// Any server instance can broadcast to all connected clients app.mcpBroadcastNotification({ jsonrpc: '2.0', method: 'notifications/message', params: { message: 'Global update from instance 2' } }) // Send to specific session (works across instances) app.mcpSendToSession('session-xyz', { jsonrpc: '2.0', method: 'notifications/progress', params: { progress: 75 } })
Implementation Design Decisions
This plugin implements certain behaviors that differ from the strict MCP specification to provide enhanced scalability and resilience in production environments:
Multiple Connections per Session
MCP Specification Intent: The official MCP specification (line 144-145) states that servers "MUST send each of its JSON-RPC messages on only one of the connected streams; that is, it MUST NOT broadcast the same message across multiple streams."
Our Implementation Choice: We allow multiple SSE connections to share the same session ID and broadcast session-specific messages (mcpSendToSession) to all connections within that session.
Why We Made This Choice:
-
Horizontal Scalability: In distributed deployments with Redis, sessions can span multiple server instances. Broadcasting ensures messages reach all connections regardless of which instance they're connected to.
-
Connection Resilience: If a client has multiple connections (e.g., main application + background tools), both can receive notifications even if one connection fails.
-
Tool Integration: External tools can join existing sessions by providing the same
mcp-session-idheader, enabling seamless integration with ongoing workflows. -
Message Persistence: All connections in a session benefit from the same message history and can replay missed events using
Last-Event-ID.
Trade-off: This approach may deliver duplicate messages to multiple connections within the same session, but the benefits in production reliability and scalability outweigh this consideration for most use cases.
Dual-Endpoint Architecture
The plugin uses a dual-endpoint architecture that separates regular MCP protocol communication from SSE streaming:
POST /mcp - MCP Protocol Communication
Handles all standard MCP protocol requests and returns JSON responses:
javascript// Regular MCP request (always returns JSON) const response = await fetch('/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'tools/call', params: { name: 'my-tool', arguments: {} }, id: 1 }) }) const result = await response.json()
GET /mcp - SSE Stream Establishment
Establishes long-lived Server-Sent Events streams for real-time communication:
javascript// Establish SSE stream (separate from protocol requests) const eventSource = new EventSource('/mcp', { headers: { 'Accept': 'text/event-stream', 'mcp-session-id': sessionId // Use session from POST request } }) eventSource.onmessage = (event) => { const message = JSON.parse(event.data) console.log('Server notification:', message) }
Complete Workflow Example
javascript// 1. Create session and make MCP requests via POST const initResponse = await fetch('/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'my-client', version: '1.0.0' } }, id: 1 }) }) const sessionId = initResponse.headers.get('mcp-session-id') // 2. Establish SSE stream for notifications via GET const eventSource = new EventSource('/mcp', { headers: { 'Accept': 'text/event-stream', 'mcp-session-id': sessionId } }) // 3. Continue making MCP requests via POST const toolResponse = await fetch('/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'mcp-session-id': sessionId }, body: JSON.stringify({ jsonrpc: '2.0', method: 'tools/call', params: { name: 'my-tool', arguments: {} }, id: 2 }) }) // Server can send notifications via the SSE stream // while client makes requests via POST
Server-Initiated Notifications
The plugin provides methods to send notifications and messages to connected SSE clients:
typescriptimport Fastify from 'fastify' import mcpPlugin from '@platformatic/mcp' const app = Fastify({ logger: true }) await app.register(mcpPlugin, { enableSSE: true, // ... other options }) // Broadcast a notification to all connected SSE clients app.mcpBroadcastNotification({ jsonrpc: '2.0', method: 'notifications/message', params: { level: 'info', message: 'Server status update' } }) // Send a message to a specific session const success = app.mcpSendToSession('session-id', { jsonrpc: '2.0', method: 'notifications/progress', params: { progressToken: 'task-123', progress: 50, total: 100 } }) // Send a request to a specific session (expecting a response) app.mcpSendToSession('session-id', { jsonrpc: '2.0', id: 'req-456', method: 'sampling/createMessage', params: { messages: [ { role: 'user', content: { type: 'text', text: 'Hello from server!' } } ] } }) // Example: Broadcast tool list changes app.mcpBroadcastNotification({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' }) // Example: Send resource updates app.mcpBroadcastNotification({ jsonrpc: '2.0', method: 'notifications/resources/updated', params: { uri: 'file://config.json' } })
Real-time Updates Example
typescript// Set up a timer to send periodic updates setInterval(() => { app.mcpBroadcastNotification({ jsonrpc: '2.0', method: 'notifications/message', params: { level: 'info', message: `Server time: ${new Date().toISOString()}` } }) }, 30000) // Every 30 seconds // Send updates when data changes function onDataChange(newData: any) { app.mcpBroadcastNotification({ jsonrpc: '2.0', method: 'notifications/resources/list_changed' }) }
Stdio Transport
The plugin includes a built-in stdio transport utility for MCP communication over stdin/stdout, following the MCP stdio transport specification. This enables command-line tools and local applications to communicate with your Fastify MCP server.
Key Features
- Complete MCP stdio transport implementation following the official specification
- Fastify integration using the
.inject()method for consistency with HTTP routes - Comprehensive error handling with proper JSON-RPC error responses
- Batch request support for processing multiple messages at once
- Debug logging to stderr without interfering with the stdio protocol
Quick Start
typescriptimport fastify from 'fastify' import mcpPlugin, { runStdioServer } from '@platformatic/mcp' const app = fastify({ logger: false // Disable HTTP logging to avoid interference with stdio }) await app.register(mcpPlugin, { serverInfo: { name: 'my-mcp-server', version: '1.0.0' }, capabilities: { tools: {}, resources: {}, prompts: {} } }) // Register your tools, resources, and prompts app.mcpAddTool({ name: 'echo', description: 'Echo back the input text', inputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] } }, async (args) => { return { content: [{ type: 'text', text: `Echo: ${args.text}` }] } }) await app.ready() // Start the stdio transport await runStdioServer(app, { debug: process.env.DEBUG === 'true' })
Usage Examples
bash# Initialize the server echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}' | node server.js # Ping the server echo '{"jsonrpc":"2.0","id":2,"method":"ping"}' | node server.js # List available tools echo '{"jsonrpc":"2.0","id":3,"method":"tools/list"}' | node server.js # Call a tool echo '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"echo","arguments":{"text":"Hello, stdio!"}}}' | node server.js
API Reference
runStdioServer(app, options)
Starts a Fastify MCP server in stdio mode.
Parameters:
app- Fastify instance with MCP plugin registeredoptions- Optional stdio transport options
Options:
debug- Enable debug logging to stderr (default: false)input- Custom input stream (default: process.stdin)output- Custom output stream (default: process.stdout)error- Custom error stream (default: process.stderr)
createStdioTransport(app, options)
Creates a stdio transport instance without starting it.
Parameters:
app- Fastify instance with MCP plugin registeredoptions- Optional stdio transport options
Returns: StdioTransport instance with start() and stop() methods
Transport Protocol
The stdio transport follows the MCP stdio transport specification:
- Messages are exchanged over stdin/stdout
- Each message is a single line of JSON
- Messages are delimited by newlines
- Messages must NOT contain embedded newlines
- Server logs can be written to stderr
- Supports both single messages and batch requests
Error Handling
The stdio transport provides comprehensive error handling:
- JSON parsing errors return appropriate JSON-RPC error responses
- Invalid method calls return "Method not found" errors
- Tool execution errors are captured and returned in the response
- Connection errors are logged to stderr
Use Cases
The stdio transport is particularly useful for:
- Command-line tools that need to communicate with MCP servers
- Local development and testing without HTTP overhead
- Integration with text editors and IDEs that support stdio protocols
- Simple client-server communication in controlled environments
- Batch processing of MCP requests from scripts
OAuth 2.1 Authorization Integration
The plugin includes comprehensive OAuth 2.1 authorization support for secure MCP communication. This enables token-based authentication, session management, and secure multi-user environments.
Key Features
- Complete OAuth 2.1 Support: Authorization Code Flow with PKCE
- Session-Based Authorization: Token-to-session mapping with secure context
- Authorization-Aware SSE: User-specific session isolation and message routing
- Automatic Token Refresh: Background token refresh with retry logic
- JWT Token Validation: Support for JWT tokens with JWKS endpoints
- Token Introspection: RFC 7662 compliant token introspection
- Dynamic Client Registration: RFC 7591 compliant client registration
- Horizontal Scaling: Redis-backed authorization context persistence
Quick OAuth Setup
typescriptimport Fastify from 'fastify' import mcpPlugin from '@platformatic/mcp' const app = Fastify({ logger: true }) await app.register(mcpPlugin, { serverInfo: { name: 'secure-mcp-server', version: '1.0.0' }, capabilities: { tools: {}, resources: {}, prompts: {} }, enableSSE: true, // Required for session-based authorization // Enable OAuth 2.1 authorization authorization: { enabled: true, authorizationServers: ['https://auth.example.com'], resourceUri: 'https://mcp.example.com', // JWT Token Validation tokenValidation: { jwksUri: 'https://auth.example.com/.well-known/jwks.json', validateAudience: true }, // OAuth 2.1 Client Configuration oauth2Client: { clientId: process.env.OAUTH_CLIENT_ID, clientSecret: process.env.OAUTH_CLIENT_SECRET, authorizationServer: 'https://auth.example.com', scopes: ['read', 'write'] } }, // Redis for session persistence (recommended) redis: { host: process.env.REDIS_HOST || 'localhost', port: parseInt(process.env.REDIS_PORT || '6379') } }) await app.listen({ port: 3000 })
Authorization Workflow
1. OAuth Authorization Flow
typescript// Start OAuth authorization const authResponse = await fetch('/oauth/authorize?redirect_uri=https://yourapp.com/dashboard') // Handle callback with authorization code const tokenResponse = await fetch('/oauth/callback', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: 'auth_code_from_callback', state: 'csrf_state_token' }) }) const { access_token, refresh_token } = await tokenResponse.json()
2. Authenticated MCP Requests
typescript// Use access token for MCP requests const mcpResponse = await fetch('/mcp', { method: 'POST', headers: { 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'tools/list', id: 1 }) })
3. Session-Based SSE Connections
typescript// SSE connection with authorization const eventSource = new EventSource('/mcp', { headers: { 'Authorization': `Bearer ${access_token}`, 'Accept': 'text/event-stream' } }) eventSource.onmessage = (event) => { const message = JSON.parse(event.data) console.log('Received:', message) } // Server can send user-specific messages // app.mcpSendToUser(userId, notification)
Authorization Configuration
JWT Token Validation
typescriptauthorization: { enabled: true, tokenValidation: { // JWKS endpoint for public key retrieval jwksUri: 'https://auth.example.com/.well-known/jwks.json', // Validate token audience validateAudience: true } }
Token Introspection (RFC 7662)
typescriptauthorization: { enabled: true, tokenValidation: { // Use token introspection instead of JWT introspectionEndpoint: 'https://auth.example.com/oauth/introspect', clientId: process.env.OAUTH_CLIENT_ID, clientSecret: process.env.OAUTH_CLIENT_SECRET } }
OAuth Client Configuration
typescriptauthorization: { enabled: true, oauth2Client: { clientId: process.env.OAUTH_CLIENT_ID, clientSecret: process.env.OAUTH_CLIENT_SECRET, // Authorization server authorizationServer: 'https://auth.example.com', // Application configuration scopes: ['read', 'write', 'admin'], // Optional: Dynamic client registration dynamicRegistration: true } }
Session-Based Authorization
The plugin maps OAuth tokens to MCP sessions for efficient authorization:
typescript// Authorization context automatically added to sessions interface SessionMetadata { id: string authorization?: { userId: string clientId: string scopes: string[] tokenHash: string // Secure hash of access token expiresAt: Date // ... additional context } tokenRefresh?: { refreshToken: string clientId: string authorizationServer: string scopes: string[] } }
User-Specific Message Routing
Send messages to specific users across all their sessions:
typescript// In your tool handler app.mcpAddTool({ name: 'notify-user', description: 'Send notification to user', inputSchema: Type.Object({ userId: Type.String(), message: Type.String() }) }, async (params, { sessionId, authContext }) => { // Send to all sessions for this user await app.mcpSendToUser(params.userId, { jsonrpc: '2.0', method: 'notifications/message', params: { level: 'info', message: params.message } }) return { content: [{ type: 'text', text: 'Notification sent' }] } })
Automatic Token Refresh
The plugin includes a background service for automatic token refresh:
typescript// Token refresh configuration authorization: { enabled: true, tokenRefresh: { // Check for expiring tokens every 5 minutes checkIntervalMs: 5 * 60 * 1000, // Refresh tokens 5 minutes before expiry refreshBufferMinutes: 5, // Maximum refresh attempts maxRetries: 3 } } // Manual token refresh const success = await app.tokenRefreshService.refreshSessionToken(sessionId) // Token refresh notifications sent via SSE // Client receives: { method: 'notifications/token_refreshed', params: { access_token: '...' } }
Authorization-Aware Tools
Access authorization context in tool handlers:
typescriptapp.mcpAddTool({ name: 'user-profile', description: 'Get user profile information', inputSchema: Type.Object({}) }, async (params, { authContext }) => { if (!authContext?.userId) { return { content: [{ type: 'text', text: 'Authentication required' }], isError: true } } // Check required scopes if (!authContext.scopes?.includes('profile:read')) { return { content: [{ type: 'text', text: 'Insufficient permissions' }], isError: true } } // Use user context const profile = await getUserProfile(authContext.userId) return { content: [{ type: 'text', text: `Profile: ${JSON.stringify(profile, null, 2)}` }] } })
Per-Tool Authorization
Tool-level checks like the one above keep the tool visible to every client and only fail at call time. To gate tools per request — hiding them from tools/list and rejecting tools/call in one place — provide a canAccessTool hook:
typescriptawait app.register(mcpPlugin, { authorization: { /* ... */ }, canAccessTool: (toolName, context) => { if (context.operation === 'list') { return canSeeTool(toolName, context.authContext) } return canExecuteTool(toolName, context.authContext) } })
The hook receives the tool name and a per-request context (authContext, request, sessionId, operation), and may be sync or async. It is consulted at both dispatch points, so list and call can never disagree:
tools/listomits every tool the hook denies for that request, calling the hook withoperation: 'list'. Per-tool checks run concurrently with a fixed cap (8 at a time), so an async hook backed by a database or HTTP service is not flooded with one lookup per registered tool; the listing keeps registration order.tools/callon a denied tool returns the same-32601"Tool 'name' not found" protocol error as an unknown tool, calling the hook withoperation: 'call'. The hook runs even for unknown names, so callers cannot probe for tools they are not allowed to see by response shape. Response timing is not guaranteed to be indistinguishable — it depends on what the hook itself does per name. Task-augmented calls (taskfield) andapp.mcpCallTool()also useoperation: 'call'.
Visibility and execution policies may intentionally diff




