TMCP (Model Context Protocol Server Implementation)

repository·main·Indexed 41 days ago

https://github.com/paoloricciuti/tmcp

A lightweight, schema-agnostic Model Context Protocol (MCP) server implementation. TMCP allows developers to build MCP servers using an adapter system to integrate preferred validation libraries such as Zod, Valibot, ArkType, and Effect Schema for JSON Schema conversion.

Tokens
98.1K
Snippets
267
Records
362
Agent score
51%

What's inside TMCP

  1. Overview of implemented MCP features in tmcp

    main

    The tmcp library is fully compliant with the MCP 2025-06-18 specification. It provides a complete implementation of the Model Context Protocol, covering core protocol requirements, server capabilities, client request capabilities, and multiple transport layers.

    Core Protocol & Server Capabilities

    • JSON-RPC 2.0: Full compliance with lifecycle management and session management using AsyncLocalStorage.
    • Tools: Full implementation of tools/list and tools/call with schema validation.
    • Resources: Complete management via resources/list, resources/read, and resources/subscribe.
    • Prompts: Full template system via prompts/list and prompts/get.
    • Resource Templates: Support for URI templates with parameter completion.
    • Notifications: List change notifications for all features.

    Client Capabilities

    • Elicitation: Interactive data collection via elicitation/create.
    • Sampling: LLM interaction requests via sampling/createMessage.
    • Roots: Client root directory inquiries via roots/list.

    Transport Layers

    • STDIO: Full message handling for CLI/Desktop environments.
    • HTTP: Support for Server-Sent Events (SSE) for web-based environments.
  2. What is tmcp?

    main

    tmcp is a modern, composable, and flexible SDK designed for building Model Context Protocol (MCP) servers. It allows developers to build servers that enable LLMs (Large Language Models) to access additional context and act on behalf of users by standardizing communication between MCP clients (like claude-code, codex, or copilot) and MCP servers.

    Key design principles of tmcp include:

    • Flexibility: You choose your deployment target, validation library, and preferred transport.
    • Modern Standards: It leverages standard patterns like the fetch API (Request/Response objects) and supports the Standard Schema specification, allowing users to use their preferred validation libraries (e.g., Valibot, Arktype, Effect, Zod).
  3. OAuth 2.1 Authorization and Security

    main

    For HTTP and SSE transports, tmcp implements a full OAuth 2.1 compliance framework. Key features include:

    • PKCE Support: Proof Key for Code Exchange for secure authorization flows.
    • Resource Indicators (RFC 8707): Support via the resource parameter for audience checking.
    • Token Management: Support for authorization code flows, refresh tokens, and token validation.
    • Client Registration: Support for dynamic client registration and multiple authentication methods.
    • Access Control: Role-based access control (RBAC) using scopes and bearer token validation.
    • CORS: Comprehensive Cross-Origin Resource Sharing configuration is integrated into the auth and transport layers.
  4. Protocol Foundation: Message Formats and Transport Layers

    main

    MCP is built on JSON-RPC 2.0 over UTF-8 encoding. The protocol supports three main message types:

    • Requests: Client-to-server or server-to-client operations with unique IDs, timeout, and cancellation support.
    • Responses: Success results or error responses with standardized error codes.
    • Notifications: One-way messages (e.g., real-time updates) that do not expect a response.

    Supported Transports

    • stdio Transport: Best for local processes and development. Uses standard input/output for efficient, low-overhead communication.
    • Streamable HTTP Transport: Best for remote servers and web integrations. Uses POST requests and optionally Server-Sent Events (SSE). Requires HTTPS and origin validation.
    • Custom Transports: Developers can implement custom transports (e.g., WebSockets, gRPC) as long as they implement JSON-RPC 2.0 message framing.
  5. Manage sessions with Redis for multi-server deployments

    main

    By default, SseTransport uses in-memory session management. For multi-server or serverless environments where sessions must be shared, use Redis-based session managers from @tmcp/session-manager-redis.

    When to use Redis sessions:

    • Multi-server deployments: When clients might connect to different instances.
    • Serverless deployments: When instances are ephemeral (though note that serverless environments may kill SSE requests quickly; streaming-http is often preferred there).
    • Load balancing: When requests are routed to different server instances.
    import {
    	RedisStreamSessionManager,
    	RedisInfoSessionManager,
    } from '@tmcp/session-manager-redis';
    
    const transport = new SseTransport(server, {
    	sessionManager: {
    		streams: new RedisStreamSessionManager('redis://localhost:6379'),
    		info: new RedisInfoSessionManager('redis://localhost:6379'),
    	},
    });
  6. Use Structured Tool Output and Resource Links

    main

    The 2025-06-18 version introduces enhanced capabilities for tool execution:

    • Structured Tool Output: Tools now support output schema validation, which improves type safety and error handling when integrating with typed languages.
    • Resource Links in Tool Results: Tools can now return resource links in their results, allowing for better integration and context sharing between tools and resources.
  7. Handle elicitation response actions

    main

    Elicitation responses follow a three-action model representing different user intentions. You should handle each case to ensure a smooth user experience:

    1. accept: The user approved and submitted the data. The content field is guaranteed to be present and valid according to your schema.
    2. decline: The user explicitly rejected the request (e.g., clicked "No" or "Reject"). Use this to offer alternatives or explain consequences.
    3. cancel: The user dismissed the dialog without making a choice (e.g., pressed Escape or closed the window). Use this to handle timeouts or provide alternative paths.
    // Example of handling all three response actions
    const response = await server.elicitation(
    	'Enter your name',
    	v.object({
    		name: v.string(),
    	}),
    );
    
    if (response.action === 'accept') {
    	// User submitted data - content is guaranteed to exist and be valid
    	console.log('Hello,', response.content!.name);
    } else if (response.action === 'decline') {
    	// User clicked "No", "Reject", or similar
    	return {
    		isError: true,
    		content: [{ type: 'text', text: 'Operation declined.' }],
    	};
    } else if (response.action === 'cancel') {
    	// User dismissed the dialog
    	return {
    		isError: true,
    		content: [{ type: 'text', text: 'Request was cancelled.' }],
    	};
    }
  8. How tmcp works: Schema Agnosticism and Adapters

    main

    Unlike the official MCP SDK, tmcp is schema-agnostic. It uses an adapter to bridge your chosen validation library (like Zod, Valibot, or ArkType) with the Model Context Protocol.

    Important Note on Adapters: An adapter is required if your server needs to:

    • Accept structured inputs
    • Produce structured outputs
    • Request elicitations

    If you pass adapter: undefined, the server will be extremely limited and cannot handle structured data. If you attempt to add a tool that uses a different validation library than the one configured in the McpServer adapter, the server will throw an error.

  9. Structured Tool Output and Resource Links

    main

    Tool results in tmcp are validated against a strict schema (CallToolResultSchema) to ensure compatibility with the MCP specification.

    Supported Features:

    • Content Types: Supports multiple content types including text, image, audio, and resource.
    • Resource Links: Tools can return resource references in their results, allowing for seamless integration between tool execution and resource access.
    • Validation: All tool outputs undergo JSON content validation and URI resolution for resource references.
  10. How session management works in TMCP

    main

    Session management in TMCP is divided into three distinct concerns to handle different aspects of transport state:

    1. Stream session managers: Handle long-lived streaming connections (like SSE/HTTP) and manage the fan-out of notifications to specific sessions.
    2. Info session managers: Persist metadata that must survive across individual HTTP requests, such as client capabilities, clientInfo, requested log levels, and resource subscriptions.
    3. Subscription managers: Route MCP 2026-07-28 per-request change notifications to long-lived subscriptions/listen streams.

    Together, these managers handle session lifecycle (creation/deletion), session queries, message delivery, and tracking resource subscriptions.