@push.rocks/smartmcp

Independent TypeScript support for tools-focused Model Context Protocol servers and clients. SmartMCP implements its own MCP wire protocol and does not depend on @modelcontextprotocol/sdk.

Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.

Install

pnpm install @push.rocks/smartmcp

SmartMCP negotiates MCP protocol revisions 2025-11-25, 2025-06-18, and 2025-03-26 for its tools-focused surface: initialization, ping, tool discovery, tool calls, progress, cancellation on persistent transports, stdio, and Streamable HTTP.

Server

createSmartMcpHttpHandler() exposes a stateless Streamable HTTP endpoint using Web-standard Request and Response objects.

import { createSmartMcpHttpHandler, z } from '@push.rocks/smartmcp';

const mcp = createSmartMcpHttpHandler({
  name: 'example-server',
  version: '1.0.0',
  trustedOrigins: ['https://app.example.com'],
  authorize: async ({ request }) => {
    const auth = request.headers.get('authorization');
    if (auth !== 'Bearer secret') {
      return new Response('Unauthorized', { status: 401 });
    }
    return { token: 'secret', clientId: 'example-client', scopes: ['mcp'] };
  },
  rateLimit: {
    capacity: 60,
    refillTokens: 60,
    refillIntervalMs: 60_000,
  },
  checkRateLimit: async ({ principal, toolName }) => {
    // Optionally enforce a distributed limit in addition to the built-in limiter.
    return { allowed: true };
  },
  tools: [
    {
      name: 'hello',
      description: 'Say hello',
      inputSchema: {
        name: z.string().describe('Name to greet'),
      },
      outputSchema: {
        greeting: z.string(),
      },
      handler: async ({ name }) => ({ greeting: `Hello ${name}` }),
    },
  ],
});

export const fetch = (request: Request) => mcp.handleRequest(request);

Object-root Zod schemas, raw Zod shapes, and object-root raw JSON Schema are supported. Raw schemas default to draft 2020-12 and may explicitly declare draft-04, draft-07, draft 2019-09, or draft 2020-12.

The Web handler is deliberately sessionless: it returns JSON responses, returns an empty 202 for notifications, and returns 405 for GET and DELETE. Because request IDs are only meaningful within a client session, cross-POST HTTP cancellation is safely ignored. Use a persistent custom transport when server-side cancellation or server-to-client requests are required.

For persistent transports, construct McpServer, register tools, and call connect(transport). registerTool() returns a handle with enable(), disable(), update(), and remove(). Tool names and callbacks are immutable; update() changes only metadata and input/output schemas.

Client

import { connectMcpClient } from '@push.rocks/smartmcp/client';

const connection = await connectMcpClient({
  type: 'streamableHttp',
  url: 'https://example.com/mcp',
  transportOptions: {
    requestInit: {
      headers: {
        authorization: `Bearer ${process.env.MCP_TOKEN}`,
      },
    },
  },
});

try {
  const tools = await connection.client.listTools();
  console.log(tools.tools.map((tool) => tool.name));
} finally {
  await connection.close();
}

Client configurations support:

  • streamableHttp or http: JSON and multi-event SSE responses, MCP-Session-Id, MCP-Protocol-Version, bounded Last-Event-ID resumption, session termination, and safe tools/list reinitialization after HTTP 404
  • stdio: newline-delimited UTF-8 JSON-RPC with bounded messages and controlled child-process shutdown
  • transport: any object implementing SmartMCP's exported structural Transport interface
  • client: a pre-created object implementing IMcpClientLike

createMcpToolClient() can discover and combine tools from multiple MCP servers, create collision-safe exposed names, dispatch calls, format results, and close all owned connections.

Security Notes

  • Incoming browser requests are same-origin by default. Add exact origins with trustedOrigins; the optional validateRequest hook runs after this built-in protection and cannot bypass it.
  • Requests without an Origin header are accepted for non-browser MCP clients by default. Set allowMissingOrigin: false if the endpoint is browser-only.
  • Use authorize for every endpoint that exposes private data. The built-in limiter keys each tool by authenticated clientId; unauthenticated callers share that tool's anonymous bucket.
  • Use checkRateLimit to add a distributed limiter keyed by the provided authenticated principal and tool name.
  • Tool arguments are validated. Structured outputs are validated when an output schema is registered. Every pre-shaped MCP result is normalized, bounded, cloned, and recursively redacted before it is returned.
  • JSON Schema tool contracts support draft-04, draft-07, draft 2019-09, and draft 2020-12. Schemas are checked against their declared dialect before registration.
  • maxRequestBytes and maxToolResultBytes bound application payloads. Transport response and stdio message limits are independently configurable.
  • SmartMCP does not auto-expose application handlers. Register an explicit allowlist of tools.

Migration from 0.2

  • Remove code that imports MCP SDK classes through SmartMCP internals. Import Client, McpServer, StdioClientTransport, StreamableHTTPClientTransport, and Transport directly from SmartMCP.
  • Replace the SDK-only authProvider transport option with requestInit, a custom fetch, or application-level authorization.
  • Structural custom transports retain the familiar start, send, close, onmessage, onerror, and onclose contract.

Third-party notices are listed in third-party-notices.md.

This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the repository license file.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.

Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.

Company Information

Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

S
Description
No description provided
Readme 166 KiB
Languages
TypeScript 100%