Logo de MCP

MCP

Organisation
platformatic

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…

Éditeurplatformatic
Dépôtmcp
LangueTypeScript
Forks
13
Étoiles
58
Outils disponibles
0
Type de transportstdio
LicenceApache-2.0
Liens
  • Connectez des outils à vos workflows IA

    MCP propose des fonctionnalités MCP utilisables par les clients et agents IA compatibles.

  • 0 outils disponibles

    Parcourez les actions invocables ci-dessous, avec leurs noms et descriptions lorsque le serveur les fournit.

  • Configuration prête à copier

    Utilisez les exemples de configuration pour configurer ce serveur dans votre client MCP préféré.

  • Indicateurs de popularité open source

    58 étoiles et 13 forks sur le dépôt associé.

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

bash
npm install @platformatic/mcp

TypeBox Support (Optional)

For type-safe schema validation, install TypeBox:

bash
npm 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-26 and 2024-11-05 for 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

typescript
import 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:

typescript
import { 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 (initialize plus notifications/initialized).
  • initialize() rejects when notifications/initialized is not accepted with an empty 202 or 204 response.
  • Commits mcp-session-id and negotiated protocol version only after the full initialization handshake succeeds.
  • Forwards headers passed to initialize() to both lifecycle requests, except MCP-managed mcp-session-id and mcp-protocol-version on notifications/initialized.
  • Captures committed mcp-session-id from 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:

typescript
import { 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-252025-11-25
tasks capabilitynot advertisedadvertised
tasks/* methods-32601 method not foundavailable
task field on tools/callignoredhonoured
icons on listingsstrippedpresent
execution.taskSupportstrippedpresent
$schema on tool schemasomittedJSON Schema 2020-12
URL mode elicitationrefusedavailable

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-26 and will not see 2025-11-25 features. 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:

typescript
await 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:

typescript
await 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":

typescript
await 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

typescript
import { 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

typescript
import { 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.

typescript
await app.register(mcpPlugin, {
  validateJsonSchemaInputs: {
    allErrors: true,
    useDefaults: false
  }
})

Behavior when enabled:

  • Invalid arguments return a tool execution error (isError: true with an Invalid 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. format keywords are annotation-only (JSON Schema 2020-12's own default).
  • A plain JSON Schema that AJV cannot compile makes mcpAddTool throw, 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

typescript
await 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

typescript
import 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/...:

typescript
import { 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), and close().
  • MemoryMessageBroker: in-process implementation backed by MQEmitter. Used automatically when no redis option is passed; messages only reach clients connected to the same server instance.
  • RedisMessageBroker: distributed implementation backed by mqemitter-redis. Used automatically when the redis option 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:

typescript
import { 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 no redis option is passed. Takes an optional maxMessages history cap (default 100).
  • RedisSessionStore: distributed implementation used automatically when the redis option 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:

  1. 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.

  2. Connection Resilience: If a client has multiple connections (e.g., main application + background tools), both can receive notifications even if one connection fails.

  3. Tool Integration: External tools can join existing sessions by providing the same mcp-session-id header, enabling seamless integration with ongoing workflows.

  4. 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:

typescript
import 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

typescript
import 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 registered
  • options - 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 registered
  • options - 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

typescript
import 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

typescript
authorization: {
  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)

typescript
authorization: {
  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

typescript
authorization: {
  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:

typescript
app.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:

typescript
await 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/list omits every tool the hook denies for that request, calling the hook with operation: '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/call on a denied tool returns the same -32601 "Tool 'name' not found" protocol error as an unknown tool, calling the hook with operation: '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 (task field) and app.mcpCallTool() also use operation: 'call'.

Visibility and execution policies may intentionally diff

Utilisez le serveur MCP MCP avec plusieurs modèles IA

TypingMind connecte les outils MCP au niveau de l’espace de travail. Une fois MCP connecté, vous pouvez donc l’utiliser avec différents modèles IA dans TypingMind sans avoir à le configurer séparément pour chaque modèle. Cette intégration MCP s’exécute localement sur votre appareil via le connecteur MCP de TypingMind.

Guide de configuration du connecteur local

Choisissez cette méthode si le serveur MCP doit accéder à des fichiers locaux, à des applications ou à des ressources privées sur votre ordinateur.

1

Ouvrir les paramètres MCP

Dans TypingMind, accédez à « Paramètres », puis à « Paramètres avancés » et à « Model Context Protocol », et choisissez « Configurer connecteur ».

  1. Ouvrez TypingMind dans votre navigateur.
  2. Cliquez sur l’icône Paramètres.
  3. Accédez aux paramètres avancés.
  4. Ouvrez la section Model Context Protocol.
  5. Cliquez sur « Configurer connecteur » et choisissez « Cet appareil ».
Écran de configuration du connecteur MCP de TypingMind avec l’option « Cet appareil » sélectionnée
2

Exécuter la commande du connecteur

Choisissez « Cet appareil », copiez la commande depuis TypingMind et exécutez-la dans Terminal. Laissez le processus en cours d’exécution pendant que vous utilisez MCP.

  1. Copiez la commande de configuration affichée par TypingMind.
  2. Ouvrez Terminal sur macOS ou Windows Terminal sur Windows.
  3. Collez et exécutez la commande.
  4. Autorisez l’installation du paquet si Terminal vous demande de confirmer.
  5. Gardez la fenêtre de Terminal ouverte et le processus en cours d’exécution pendant que vous utilisez les outils MCP.
3

Ajoutez MCP en tant que serveur

Lorsque l’état du connecteur affiche « Prêt », cliquez sur « Éditer serveurs » et collez la configuration du serveur MCP.

  1. Attendez que l’état du connecteur affiche « Prêt ».
  2. Cliquez sur « Éditer serveurs ».
  3. Collez la configuration du serveur MCP MCP.
  4. Enregistrez la liste des serveurs.
  5. Actualisez pour vérifier que le connecteur est toujours prêt.
Paramètres MCP de TypingMind affichant un serveur actif et le bouton « Éditer serveurs »
{
  "mcpServers": {
    "platformatic-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Utiliser la connexion avec différents modèles

Enregistrez la liste des serveurs, ouvrez « Plugins », activez les outils MCP de MCP, puis sélectionnez un modèle IA compatible dans TypingMind et utilisez les outils dans une discussion ou attribuez-les à un agent IA.

  1. Ouvrez la page Plugins dans TypingMind.
  2. Activez les outils MCP de MCP.
  3. Démarrez une discussion et choisissez le modèle IA que vous souhaitez utiliser.
  4. Utilisez les outils MCP dans le chat ou attribuez-les à un agent IA.
  5. Passez à un autre modèle IA selon vos besoins sans rétablir la connexion MCP.
Discussion TypingMind utilisant des outils MCP activés avec un modèle d’IA sélectionné
Pouvez-vous utiliser MCP pour m’aider dans cette tâche ?
MCP
Bien sûr. J’ai tout lu.
Voici ce que j’ai trouvé avec MCP.

Foire aux questions

À quoi sert le serveur MCP MCP ?

MCP est un serveur MCP qui permet aux applications IA compatibles d’accéder à des outils et à des informations contextuelles externes. Dans TypingMind, il vous suffit d’ajouter ce serveur MCP une seule fois pour rendre ses outils disponibles dans votre espace de travail IA.

Puis-je utiliser le serveur MCP MCP avec plusieurs modèles IA dans TypingMind ?

Oui. TypingMind connecte les outils MCP au niveau de l’espace de travail. Vous pouvez donc utiliser MCP avec différents modèles IA comme Claude, ChatGPT, Gemini ou d’autres modèles configurés dans TypingMind, sans avoir à configurer le serveur MCP séparément pour chaque modèle.

Pourquoi utiliser le connecteur MCP MCP avec TypingMind ?

TypingMind est l’une des meilleures interfaces de chat avec les LLM, car elle réunit plusieurs modèles IA, prompts, plugins, agents IA, clés API et outils MCP dans un seul espace de travail. Une fois MCP connecté, vous pouvez utiliser ses outils MCP avec vos modèles préférés tout en gardant vos discussions bien organisées dans TypingMind.

Comment connecter le serveur MCP MCP à TypingMind ?

MCP fonctionne via le connecteur MCP local de TypingMind. C’est l’option idéale lorsque le serveur MCP doit accéder à des fichiers locaux, des applications de bureau, des outils en ligne de commande ou des ressources privées sur votre ordinateur.

Quels outils le serveur MCP MCP propose-t-il dans TypingMind ?

MCP propose des fonctionnalités MCP que vous pouvez activer depuis la page Plugins de TypingMind et utiliser dans les discussions ou attribuer à des agents IA.

Dois-je partager mes clés API avec TypingMind pour utiliser le serveur MCP MCP ?

Non. TypingMind privilégie le fonctionnement local et vous permet de garder le contrôle de vos fournisseurs de modèles, clés API, prompts et paramètres MCP. Si MCP nécessite une authentification, ajoutez les en-têtes, les paramètres OAuth ou la configuration locale requis pour ce serveur MCP lors de la création de la connexion.

Serveurs MCP similaires

Tout voir

Créez votre propre espace IA dès maintenant

Abonnez-vous à notre newsletter pour être informé des nouvelles fonctionnalités et des prochains cadeaux à gagner 👇