{"id":28898832,"url":"https://github.com/flaviodelgrosso/fastify-mcp-server","last_synced_at":"2026-04-16T04:02:01.188Z","repository":{"id":299201932,"uuid":"1000078574","full_name":"flaviodelgrosso/fastify-mcp-server","owner":"flaviodelgrosso","description":"Fastify plugin to easily spin up Model Context Protocol (MCP) HTTP servers","archived":false,"fork":false,"pushed_at":"2026-04-08T16:52:04.000Z","size":726,"stargazers_count":26,"open_issues_count":7,"forks_count":7,"subscribers_count":1,"default_branch":"master","last_synced_at":"2026-04-08T18:36:02.103Z","etag":null,"topics":["fastify","http","mcp","modelcontextprotocol","nodejs","server","streamable-http"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/fastify-mcp-server","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"isc","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/flaviodelgrosso.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-06-11T08:28:05.000Z","updated_at":"2026-04-06T05:37:53.000Z","dependencies_parsed_at":"2025-12-27T15:05:30.964Z","dependency_job_id":null,"html_url":"https://github.com/flaviodelgrosso/fastify-mcp-server","commit_stats":null,"previous_names":["flaviodelgrosso/fastify-mcp-streamable-http","flaviodelgrosso/fastify-mcp-server"],"tags_count":11,"template":false,"template_full_name":null,"purl":"pkg:github/flaviodelgrosso/fastify-mcp-server","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flaviodelgrosso%2Ffastify-mcp-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flaviodelgrosso%2Ffastify-mcp-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flaviodelgrosso%2Ffastify-mcp-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flaviodelgrosso%2Ffastify-mcp-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/flaviodelgrosso","download_url":"https://codeload.github.com/flaviodelgrosso/fastify-mcp-server/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/flaviodelgrosso%2Ffastify-mcp-server/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31870516,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-15T15:24:51.572Z","status":"online","status_checked_at":"2026-04-16T02:00:06.042Z","response_time":69,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastify","http","mcp","modelcontextprotocol","nodejs","server","streamable-http"],"created_at":"2025-06-21T08:00:29.786Z","updated_at":"2026-04-16T04:02:01.168Z","avatar_url":"https://github.com/flaviodelgrosso.png","language":"TypeScript","funding_links":[],"categories":["📚 Projects (1974 total)"],"sub_categories":["MCP Servers"],"readme":"# Fastify MCP Server Plugin\n\nA robust Fastify plugin that provides seamless integration with the Model Context Protocol (MCP) through streamable HTTP transport. This plugin enables your Fastify applications to act as MCP servers, allowing AI assistants and other clients to interact with your services using the standardized MCP protocol.\n\n[![NPM version](https://img.shields.io/npm/v/fastify-mcp-server.svg?style=flat)](https://www.npmjs.com/package/fastify-mcp-server)\n[![NPM downloads](https://img.shields.io/npm/dm/fastify-mcp-server.svg?style=flat)](https://www.npmjs.com/package/fastify-mcp-server)\n[![CI](https://github.com/flaviodelgrosso/fastify-mcp-server/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/flaviodelgrosso/fastify-mcp-server/actions/workflows/ci.yml)\n[![codecov](https://codecov.io/gh/flaviodelgrosso/fastify-mcp-server/graph/badge.svg?token=4ZGUR6VXTJ)](https://codecov.io/gh/flaviodelgrosso/fastify-mcp-server)\n\n## Table of Contents\n\n- [Fastify MCP Server Plugin](#fastify-mcp-server-plugin)\n  - [Table of Contents](#table-of-contents)\n  - [Overview](#overview)\n  - [Features](#features)\n    - [Core Functionality](#core-functionality)\n    - [Advanced Features](#advanced-features)\n  - [Installation](#installation)\n  - [Quick Demo](#quick-demo)\n  - [Quick Start](#quick-start)\n  - [API Reference](#api-reference)\n    - [Plugin Options](#plugin-options)\n    - [MCP Decorator](#mcp-decorator)\n    - [Session Events](#session-events)\n  - [HTTP Protocol](#http-protocol)\n    - [POST `/mcp`](#post-mcp)\n    - [GET `/mcp`](#get-mcp)\n    - [DELETE `/mcp`](#delete-mcp)\n    - [Session Management](#session-management)\n  - [Advanced Usage](#advanced-usage)\n    - [Custom Error Handling](#custom-error-handling)\n    - [Health Monitoring](#health-monitoring)\n    - [Graceful Shutdown](#graceful-shutdown)\n  - [Session Storage](#session-storage)\n    - [Built-in Session Stores](#built-in-session-stores)\n      - [In-Memory Session Store (Default)](#in-memory-session-store-default)\n      - [Redis Session Store](#redis-session-store)\n    - [Custom Session Store](#custom-session-store)\n    - [How It Works](#how-it-works)\n    - [Comparison](#comparison)\n    - [Docker Compose Example](#docker-compose-example)\n  - [Authentication: Bearer Token Support](#authentication-bearer-token-support)\n    - [Enabling Bearer Token Authentication](#enabling-bearer-token-authentication)\n    - [How It Works](#how-it-works-1)\n      - [Example Tool with authentication information](#example-tool-with-authentication-information)\n      - [Example Error Response](#example-error-response)\n      - [Example using PAT in Visual Studio Code](#example-using-pat-in-visual-studio-code)\n  - [Well-Known OAuth Metadata Routes](#well-known-oauth-metadata-routes)\n    - [Registering Well-Known Routes](#registering-well-known-routes)\n    - [Endpoints](#endpoints)\n  - [Custom Transport Options](#custom-transport-options)\n    - [Available Options](#available-options)\n    - [Use Cases](#use-cases)\n    - [Example: Custom Session ID with Prefix](#example-custom-session-id-with-prefix)\n  - [Development](#development)\n    - [Setup](#setup)\n    - [Scripts](#scripts)\n    - [Testing](#testing)\n  - [Contributing](#contributing)\n  - [License](#license)\n  - [Related Projects](#related-projects)\n\n## Overview\n\nThe Model Context Protocol (MCP) is an open standard that enables AI assistants to securely connect to external data sources and tools. This plugin provides a streamable HTTP transport implementation for MCP servers built with Fastify, offering:\n\n- **High Performance**: Built on top of Fastify's high-performance HTTP server\n- **Session Management**: Automatic handling of MCP sessions with proper lifecycle management\n- **Event-Driven Architecture**: Real-time session monitoring and error handling\n- **Type Safety**: Full TypeScript support with comprehensive type definitions\n- **Production Ready**: Robust error handling, graceful shutdown, and monitoring capabilities\n\n## Features\n\n### Core Functionality\n\n- ✅ **MCP Server Integration**: Seamless integration with `@modelcontextprotocol/sdk`\n- ✅ **Streamable HTTP Transport**: Full support for MCP's streamable HTTP protocol\n- ✅ **Session Management**: Automatic session creation, tracking, and cleanup\n- ✅ **Session Storage**: Support for in-memory and custom session stores (Redis included)\n- ✅ **Request Routing**: Intelligent routing for different MCP request types\n- ✅ **Authentication**: Optional Bearer token support for secure access\n- ✅ **Error Handling**: Comprehensive error handling with proper MCP error responses\n\n### Advanced Features\n\n- ✅ **Event System**: Listen to session lifecycle events (creation, destruction, errors)\n- ✅ **Session Statistics**: Real-time monitoring of active sessions\n- ✅ **Graceful Shutdown**: Proper cleanup of all sessions during server shutdown\n- ✅ **Configurable Endpoints**: Customizable MCP endpoint paths\n- ✅ **Custom Session Stores**: Implement your own session storage backend\n- ✅ **Custom Transport Options**: Configure transport behavior with custom session ID generation and callbacks\n- ✅ **TypeScript Support**: Full type safety and IntelliSense support\n\n## Installation\n\n```bash\nnpm install fastify-mcp-server @modelcontextprotocol/sdk\n```\n\n## Quick Demo\n\nTo quickly see the plugin in action, you can run the demo server:\n\n```bash\n# Run with in-memory session storage\nnpm run dev\n\n# Run with Redis session storage\nnpm run dev:redis\n\n# Start MCP inspector to interact with the server\nnpm run inspector\n```\n\nThis will start a Fastify server with the MCP plugin enabled, allowing you to interact with it via the MCP inspector or any MCP-compatible client.\n\n## Quick Start\n\n```typescript\nimport Fastify from 'fastify';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport FastifyMcpServer, { getMcpDecorator } from 'fastify-mcp-server';\n\nconst app = Fastify({ logger: true });\n\n// Create MCP server factory function\nfunction createMcpServer () {\n  const mcp = new McpServer({\n    name: 'my-mcp-server',\n    version: '1.0.0'\n  });\n\n  // Define MCP tools\n  mcp.tool('hello-world', () =\u003e ({\n    content: [{ type: 'text', text: 'Hello from MCP!' }]\n  }));\n\n  return mcp;\n}\n\n// Register the plugin\nawait app.register(FastifyMcpServer, {\n  createMcpServer,\n  endpoint: '/mcp' // optional, defaults to '/mcp'\n});\n\n// Get MCP decorator for advanced features\nconst mcpServer = getMcpDecorator(app);\n\n// Start the server\nawait app.listen({ host: '127.0.0.1', port: 3000 });\n```\n\n## API Reference\n\n### Plugin Options\n\n```typescript\ntype FastifyMcpServerOptions = {\n  createMcpServer: () =\u003e McpServer; // MCP Server factory function\n  endpoint?: string; // Custom endpoint path (default: '/mcp')\n  authorization?: {\n    // Authorization configuration\n    bearerMiddlewareOptions: {\n      verifier: OAuthTokenVerifier; // Custom verifier for Bearer tokens\n      requiredScopes?: string[]; // Optional scopes required for access\n      resourceMetadataUrl?: string; // Optional URL for resource metadata\n    };\n    oauth2?: {\n      // OAuth2 metadata configuration\n      authorizationServerOAuthMetadata: OAuthMetadata; // OAuth metadata for authorization server\n      protectedResourceOAuthMetadata: OAuthProtectedResourceMetadata; // OAuth metadata for protected resource\n    };\n  };\n  sessionStore?: SessionStore; // Optional custom session store implementation\n  transportOptions?: StreamableHTTPServerTransportOptions; // Optional transport configuration options\n};\n```\n\n### MCP Decorator\n\nThe plugin decorates your Fastify instance with an MCP server that provides several useful methods:\n\n```typescript\nconst mcpServer = getMcpDecorator(app);\n\n// Get session statistics\nconst stats = mcpServer.getStats();\nconsole.log(`Active sessions: ${stats.activeSessions}`);\n\n// Access session manager for event handling\nconst sessionManager = mcpServer.getSessionManager();\n\n// Create a new MCP server instance (useful for per-session customization)\nconst newMcpInstance = mcpServer.create();\n```\n\n### Session Events\n\nMonitor session lifecycle with event listeners:\n\n```typescript\nconst sessionManager = mcpServer.getSessionManager();\n\n// Session created\nsessionManager.on('sessionCreated', (sessionId: string) =\u003e {\n  console.log(`New MCP session: ${sessionId}`);\n});\n\n// Session destroyed\nsessionManager.on('sessionDestroyed', (sessionId: string) =\u003e {\n  console.log(`MCP session ended: ${sessionId}`);\n});\n\n// Transport errors\nsessionManager.on('transportError', (sessionId: string, error: Error) =\u003e {\n  console.error(`Error in session ${sessionId}:`, error);\n});\n```\n\n## HTTP Protocol\n\nThe plugin exposes three HTTP endpoints for MCP communication:\n\n### POST `/mcp`\n\n- **Purpose**: Create new sessions or send requests to existing sessions\n- **Headers**:\n  - `content-type: application/json`\n  - `mcp-session-id: \u003csession-id\u003e` (optional, for existing sessions)\n- **Body**: MCP request payload\n\n### GET `/mcp`\n\n- **Purpose**: Retrieve streaming responses\n- **Headers**:\n  - `mcp-session-id: \u003csession-id\u003e` (required)\n- **Response**: Server-sent events stream\n\n### DELETE `/mcp`\n\n- **Purpose**: Terminate sessions\n- **Headers**:\n  - `mcp-session-id: \u003csession-id\u003e` (required)\n\n### Session Management\n\nSessions are managed through a dedicated `SessionManager` class that:\n\n- **Creates** new transport instances with unique session IDs\n- **Tracks** active sessions in memory\n- **Handles** session lifecycle events\n- **Provides** graceful cleanup on shutdown\n- **Emits** events for monitoring and logging\n\n## Advanced Usage\n\n### Custom Error Handling\n\n```typescript\nsessionManager.on('transportError', (sessionId, error) =\u003e {\n  console.error(`Transport error: ${error.message}`);\n});\n```\n\n### Health Monitoring\n\n```typescript\n// Periodic health check\nsetInterval(() =\u003e {\n  const stats = mcpServer.getStats();\n  console.log(`Health Check - Active Sessions: ${stats.activeSessions}`);\n\n  // Alert if too many sessions\n  if (stats.activeSessions \u003e 100) {\n    console.warn('High session count detected');\n  }\n}, 30000);\n```\n\n### Graceful Shutdown\n\n```typescript\nimport closeWithGrace from 'close-with-grace';\n\ncloseWithGrace({ delay: 500 }, async ({ signal, err }) =\u003e {\n  if (err) {\n    app.log.error({ err }, 'server closing with error');\n  } else {\n    app.log.info(`${signal} received, server closing`);\n  }\n\n  // Fastify close will handle MCP session cleanup automatically\n  await app.close();\n});\n```\n\n## Session Storage\n\nThe plugin provides a flexible session storage system that allows you to choose or implement your own storage backend. By default, sessions are stored in memory, but you can use Redis or create your own custom implementation.\n\n### Built-in Session Stores\n\n#### In-Memory Session Store (Default)\n\n```typescript\nimport { InMemorySessionStore } from 'fastify-mcp-server';\n\nawait app.register(FastifyMcpServer, {\n  createMcpServer\n  // sessionStore option is optional - InMemorySessionStore is used by default\n});\n```\n\n#### Redis Session Store\n\nFor production deployments or distributed systems, use the Redis session store:\n\n```typescript\nimport { RedisSessionStore } from 'fastify-mcp-server';\n\nconst redisStore = new RedisSessionStore(redisClient); // Pass your Redis client instance\n\nawait app.register(FastifyMcpServer, {\n  createMcpServer,\n  sessionStore: redisStore\n});\n```\n\n### Custom Session Store\n\nYou can implement your own session store by implementing the `SessionStore` interface:\n\n```typescript\nimport type { SessionStore, SessionData } from 'fastify-mcp-server';\n\nclass MyCustomSessionStore implements SessionStore {\n  async load (sessionId: string): Promise\u003cSessionData | undefined\u003e {\n    // Load session from your storage backend\n  }\n\n  async save (sessionData: SessionData): Promise\u003cvoid\u003e {\n    // Save session to your storage backend\n  }\n\n  async delete (sessionId: string): Promise\u003cvoid\u003e {\n    // Delete session from your storage backend\n  }\n\n  async getAllSessionIds (): Promise\u003cstring[]\u003e {\n    // Return all session IDs\n  }\n\n  async deleteAll (): Promise\u003cvoid\u003e {\n    // Delete all sessions\n  }\n}\n\n// Use your custom store\nawait app.register(FastifyMcpServer, {\n  createMcpServer,\n  sessionStore: new MyCustomSessionStore()\n});\n```\n\n### How It Works\n\nThe session store is responsible for persisting session metadata (session ID and creation time). The plugin manages transports and MCP server connections in memory for performance, while session metadata can be stored in your chosen backend.\n\n- **Session Creation**: When a client initializes, session metadata is saved to the store\n- **Session Retrieval**: Session data is loaded from the store to validate existing sessions\n- **Session Cleanup**: Sessions are removed from the store when destroyed\n- **Transport Management**: Active transports are maintained in memory for fast access\n\n### Comparison\n\n| Feature         | In-Memory                    | Redis                           | Custom                       |\n| --------------- | ---------------------------- | ------------------------------- | ---------------------------- |\n| **Persistence** | Lost on restart              | Persists across restarts        | Depends on implementation    |\n| **Scalability** | Single instance              | Multiple instances              | Depends on implementation    |\n| **Performance** | Fastest                      | Slightly slower (network)       | Depends on implementation    |\n| **Use Case**    | Development, single instance | Production, distributed systems | Specialized requirements     |\n| **Setup**       | No configuration needed      | Requires Redis server           | Custom implementation needed |\n\n### Docker Compose Example\n\nA `docker-compose.yaml` is provided for local development with Redis:\n\n```bash\ndocker compose up -d\nnpm run dev:redis\n```\n\n## Authentication: Bearer Token Support\n\nYou can secure your MCP endpoints using Bearer token authentication. The plugin provides a `bearerMiddlewareOptions` option, which enables validation of Bearer tokens in the `Authorization` header for all MCP requests.\n\n### Enabling Bearer Token Authentication\n\nPass the `authorization.bearerMiddlewareOptions` option when registering the plugin. It accepts `BearerAuthMiddlewareOptions` from the SDK:\n\n```typescript\nimport type { BearerAuthMiddlewareOptions } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';\n```\n\n```typescript\nawait app.register(FastifyMcpServer, {\n  createMcpServer,\n  authorization: {\n    bearerMiddlewareOptions: {\n      verifier: myVerifier, // implements verifyAccessToken(token)\n      requiredScopes: ['mcp:read', 'mcp:write'], // optional\n      resourceMetadataUrl: 'https://example.com/.well-known/oauth-resource' // optional\n    }\n  }\n});\n```\n\n- **verifier**: An object with a `verifyAccessToken(token)` method that returns the decoded token info or throws on failure. It must implements the `OAuthTokenVerifier` interface from the SDK.\n- **requiredScopes**: (Optional) Array of scopes required for access.\n- **resourceMetadataUrl**: (Optional) URL included in the `WWW-Authenticate` header for 401 responses.\n\n### How It Works\n\nThe plugin uses a Fastify `preHandler` hook applied in the context of the MCP registered routes (see `addBearerPreHandlerHook`) to:\n\n- Extract the Bearer token from the `Authorization` header (`Authorization: Bearer TOKEN`).\n- Validate the token using your verifier.\n- Check for required scopes and token expiration.\n- Attach the decoded auth info to the request object (`req.raw.auth`).\n- Respond with proper OAuth2 error codes and `WWW-Authenticate` headers on failure.\n\n#### Example Tool with authentication information\n\nYou can access the validated authentication information in your MCP tools via the `authInfo` parameter:\n\n```typescript\nmcp.tool('example-auth-tool', 'Demo to display the validated access token in authInfo object', ({ authInfo }) =\u003e {\n  return {\n    content: [\n      {\n        type: 'text',\n        // Just a bad example, do not expose sensitive information in your LLM responses! :-)\n        text: `Authenticated with token: ${authInfo.token}, scopes: ${authInfo.scopes.join(', ')}, expires at: ${new Date(authInfo.expiresAt).toISOString()}`\n      }\n    ]\n  };\n});\n```\n\n#### Example Error Response\n\nIf authentication fails, the response will include a `WWW-Authenticate` header:\n\n```txt\nHTTP/1.1 401 Unauthorized\nWWW-Authenticate: Bearer error=\"invalid_token\", error_description=\"Token has expired\"\nContent-Type: application/json\n\n{\"error\":\"invalid_token\",\"error_description\":\"Token has expired\"}\n```\n\n#### Example using PAT in Visual Studio Code\n\n```json\n{\n  \"inputs\": [\n    {\n      \"type\": \"promptString\",\n      \"id\": \"bearer_token\",\n      \"description\": \"Enter your MCP Bearer Token\",\n      \"password\": true\n    }\n  ],\n  \"servers\": {\n    \"my-mcp-server\": {\n      \"url\": \"http://localhost:9080/mcp\",\n      \"headers\": {\n        \"Authorization\": \"Bearer ${input:bearer_token}\"\n      }\n    }\n  }\n}\n```\n\n## Well-Known OAuth Metadata Routes\n\nThe plugin can automatically register standard OAuth 2.0 metadata endpoints under the `.well-known` path, which are useful for interoperability with OAuth clients and resource servers. You can test metadata discovery with the MCP inspector in the `Authentication` tab.\n\n### Registering Well-Known Routes\n\nTo enable these endpoints, provide the `authorization.oauth2.authorizationServerOAuthMetadata` and/or `authorization.oauth2.protectedResourceOAuthMetadata` options when registering the plugin:\n\n```typescript\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport FastifyMcpServer from 'fastify-mcp-server';\n\nfunction createMcpServer () {\n  return new McpServer({\n    name: 'my-mcp-server',\n    version: '1.0.0'\n  });\n}\n\nconst authorizationServerMetadata = {\n  issuer: 'https://your-domain.com',\n  authorization_endpoint: 'https://your-domain.com/oauth/authorize',\n  token_endpoint: 'https://your-domain.com/oauth/token'\n  // ...other OAuth metadata fields\n};\n\nconst protectedResourceMetadata = {\n  resource: 'https://your-domain.com/.well-known/oauth-protected-resource'\n  // ...other resource metadata fields\n};\n\nawait app.register(FastifyMcpServer, {\n  createMcpServer,\n  authorization: {\n    oauth2: {\n      authorizationServerOAuthMetadata: authorizationServerMetadata, // Registers /.well-known/oauth-authorization-server\n      protectedResourceOAuthMetadata: protectedResourceMetadata // Registers /.well-known/oauth-protected-resource\n    }\n  }\n});\n```\n\n### Endpoints\n\n- `GET /.well-known/oauth-authorization-server` — Returns the OAuth authorization server metadata.\n- `GET /.well-known/oauth-protected-resource` — Returns the OAuth protected resource metadata.\n\nThese endpoints are registered only if the corresponding metadata options are provided.\n\n## Custom Transport Options\n\nYou can customize the behavior of the underlying `StreamableHTTPServerTransport` by providing `transportOptions` when registering the plugin. This allows you to configure advanced transport features such as custom session ID generation and transport lifecycle callbacks.\n\n### Available Options\n\n```typescript\nimport type { StreamableHTTPServerTransportOptions } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\n\nawait app.register(FastifyMcpServer, {\n  createMcpServer,\n  transportOptions: {\n    // Custom session ID generator function\n    sessionIdGenerator: () =\u003e {\n      // Return your custom session ID\n      return `custom-${Date.now()}-${Math.random()}`;\n    },\n    // Callback invoked when session is initialized\n    onsessioninitialized: async (sessionId) =\u003e {\n      console.log(`Session ${sessionId} initialized`);\n    }\n    // Additional StreamableHTTPServerTransport options...\n  }\n});\n```\n\n### Use Cases\n\n- **Custom Session IDs**: Generate session IDs that match your existing ID format or include specific metadata\n- **Session Initialization Hooks**: Perform custom logic when sessions are created (e.g., logging, metrics, notifications)\n- **Transport Configuration**: Fine-tune transport behavior for specific deployment requirements\n\n### Example: Custom Session ID with Prefix\n\n```typescript\nawait app.register(FastifyMcpServer, {\n  createMcpServer,\n  transportOptions: {\n    sessionIdGenerator: () =\u003e {\n      return `mcp-prod-${randomUUID()}`;\n    }\n  }\n});\n```\n\n## Development\n\n### Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/flaviodelgrosso/fastify-mcp-server.git\ncd fastify-mcp-server\n\n# Install dependencies\nnpm install\n\n# Run development server with hot reload\nnpm run dev\n```\n\n### Scripts\n\n- `npm run dev` - Run development server with in-memory session storage\n- `npm run dev:redis` - Run development server with Redis session storage\n- `npm run build` - Build TypeScript to JavaScript\n- `npm test` - Run test suite with 100% coverage\n- `npm run test:lcov` - Generate LCOV coverage report\n- `npm run inspector` - Launch MCP inspector for testing\n\n### Testing\n\nThe project maintains 100% test coverage. Run tests with:\n\n```bash\nnpm test\n```\n\n## Contributing\n\nContributions are welcome! Please read our contributing guidelines and ensure:\n\n1. Tests pass with 100% coverage\n2. Code follows the established style (enforced by Biome)\n3. Commits follow conventional commit format\n4. Changes are properly documented\n\n## License\n\nISC © [Flavio Del Grosso](https://github.com/flaviodelgrosso)\n\n## Related Projects\n\n- [Model Context Protocol](https://github.com/modelcontextprotocol/servers) - Official MCP specification and servers\n- [Fastify](https://github.com/fastify/fastify) - Fast and low overhead web framework\n- [MCP SDK](https://github.com/modelcontextprotocol/typescript-sdk) - TypeScript SDK for MCP\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflaviodelgrosso%2Ffastify-mcp-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fflaviodelgrosso%2Ffastify-mcp-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflaviodelgrosso%2Ffastify-mcp-server/lists"}