@modelcontextprotocol/sdk vs mcp-framework
Building Model Context Protocol Servers in JavaScript
@modelcontextprotocol/sdkmcp-framework

Building Model Context Protocol Servers in JavaScript

@modelcontextprotocol/sdk is the official low-level software development kit for the Model Context Protocol (MCP), maintained by the protocol creators. It provides core classes for building MCP clients and servers with full control over transports and message handling. mcp-framework is a community-built wrapper designed to simplify server creation by reducing boilerplate code and automating transport setup. Both enable AI models to connect with external data sources, but they differ in abstraction level and maintenance backing.

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
@modelcontextprotocol/sdk36,034,00012,4214.27 MB3831 个月前MIT
mcp-framework58,798916352 kB141 个月前-

Building MCP Servers: Official SDK vs Community Framework

Connecting AI models to external data requires a stable interface. The Model Context Protocol (MCP) provides this standard. When building servers in JavaScript, you generally choose between the official @modelcontextprotocol/sdk and community wrappers like mcp-framework. Let's compare how they handle setup, tool definitions, and server lifecycle.

🏗️ Server Initialization and Transport

@modelcontextprotocol/sdk requires you to manually configure the transport layer.

  • You must import the specific transport (like Stdio or SSE).
  • You explicitly connect the server to the transport.
  • This gives you full control but adds boilerplate.
// @modelcontextprotocol/sdk: Manual transport setup
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new Server(
  { name: "my-server", version: "1.0.0" },
  { capabilities: { tools: {} } }
);

const transport = new StdioServerTransport();
await server.connect(transport);

mcp-framework abstracts the transport logic away.

  • You initialize a single app instance.
  • The framework handles the connection details automatically.
  • Less code to write, but less visibility into the connection process.
// mcp-framework: Auto transport setup
import { MCP } from "mcp-framework";

const app = new MCP({
  name: "my-server",
  version: "1.0.0"
});

// Transport is handled internally
await app.start();

🛠️ Defining Tools and Capabilities

@modelcontextprotocol/sdk uses explicit schema validators for tools.

  • You define input schemas using Zod or similar libraries.
  • You register handlers for specific request types.
  • This ensures type safety but requires more verbose setup.
// @modelcontextprotocol/sdk: Explicit schema
import { z } from "zod";
import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";

server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "get_weather",
        description: "Get weather data",
        inputSchema: z.object({ city: z.string() }).shape
      }
    ]
  };
});

mcp-framework often simplifies tool registration with decorators or methods.

  • You call a method like app.tool() directly.
  • Schema validation might be inferred or simplified.
  • Faster to write, but might hide complex validation rules.
// mcp-framework: Simplified registration
app.tool("get_weather", {
  description: "Get weather data",
  params: { city: "string" }
}, async (args) => {
  return { data: `Weather in ${args.city}` };
});

🔄 Error Handling and Lifecycle

@modelcontextprotocol/sdk exposes raw protocol errors.

  • You catch errors at the transport or request level.
  • You decide how to log or respond to failures.
  • More work, but you know exactly what failed.
// @modelcontextprotocol/sdk: Manual error handling
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  try {
    // Tool logic
    return { content: [] };
  } catch (error) {
    console.error("Tool failed:", error);
    throw error; // Propagates to MCP client
  }
});

mcp-framework often includes global error hooks.

  • You define a single error handler for all tools.
  • The framework catches unhandled exceptions.
  • Easier to manage, but might swallow specific details.
// mcp-framework: Global error hook
app.onError((error, toolName) => {
  console.error(`Tool ${toolName} failed:`, error);
  // Framework handles response formatting
});

📦 Maintenance and Protocol Updates

@modelcontextprotocol/sdk is updated directly by the protocol maintainers.

  • New protocol features arrive here first.
  • Breaking changes are documented in official release notes.
  • Best for long-term projects requiring stability.
// @modelcontextprotocol/sdk: Direct access to new features
// When protocol updates, you update this package
import { NewFeatureSchema } from "@modelcontextprotocol/sdk/types.js";

mcp-framework depends on the community maintainer updating the wrapper.

  • There may be a delay between protocol updates and framework support.
  • You rely on the wrapper author to fix bugs.
  • Riskier for critical infrastructure.
// mcp-framework: Waiting for wrapper update
// You might need to wait for the framework to support new protocol features
// or drop down to the underlying SDK manually

🌱 Similarities: Shared Core Concepts

Despite the differences in abstraction, both packages rely on the same underlying protocol standards.

1. 🔌 JSON-RPC 2.0 Foundation

  • Both communicate using JSON-RPC 2.0 messages.
  • Requests and responses follow the same structure.
// Both send standard JSON-RPC payloads
// { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }

2. 🔒 Security Models

  • Both require secure transport configuration for production.
  • Neither exposes tools to the public internet by default without setup.
// Both require explicit transport config for network access
// SDK: new SseServerTransport()
// Framework: app.configure({ transport: 'sse' })

3. 🧩 Tool Definitions

  • Both define tools with names, descriptions, and input schemas.
  • AI models interact with the tools in the same way regardless of the package.
// Tool shape is consistent across both
// { name: "...", description: "...", inputSchema: {...} }

📊 Summary: Key Differences

Feature@modelcontextprotocol/sdkmcp-framework
Maintenance🟢 Official Team🟡 Community Maintainer
Setup🛠️ Manual Transport⚡ Auto Transport
Tool Definition📝 Explicit Schemas🚀 Simplified Methods
Control🎛️ Full Low-Level Access📦 Abstracted
Update Speed🚀 Immediate Protocol Support⏳ Depends on Wrapper
Best For🏢 Production Systems🧪 Prototypes & Internal Tools

💡 The Big Picture

@modelcontextprotocol/sdk is like building with raw materials 🧱 — you have full control over every brick and beam. It is the right choice for teams building critical infrastructure where stability and direct protocol support are non-negotiable.

mcp-framework is like using a prefabricated kit 🏠 — you get walls and roofs instantly. It is perfect for hacking together a quick demo or internal tool where speed matters more than long-term maintenance guarantees.

Final Thought: If you are building something you plan to maintain for years, stick with the official SDK. If you need to show a working prototype by tomorrow, the framework will get you there faster — just be ready to refactor later.

如何选择: @modelcontextprotocol/sdk vs mcp-framework

  • @modelcontextprotocol/sdk:

    Choose the official SDK if you need long-term stability, full control over transport layers, and direct alignment with protocol updates. It is the safest choice for production systems where reliability and official support matter most. You will write more setup code, but you avoid dependencies on third-party abstractions that might lag behind protocol changes.

  • mcp-framework:

    Choose mcp-framework if you want to prototype quickly or prefer a simpler API that hides transport complexity. It is suitable for internal tools or experiments where developer speed is more important than strict adherence to the official maintenance cycle. Be aware that community wrappers may require more effort to update when the core protocol changes.

@modelcontextprotocol/sdk的README

MCP TypeScript SDK NPM Version MIT licensed

Table of Contents

Overview

The Model Context Protocol allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. This TypeScript SDK implements the full MCP specification, making it easy to:

  • Create MCP servers that expose resources, prompts and tools
  • Build MCP clients that can connect to any MCP server
  • Use standard transports like stdio and Streamable HTTP

Installation

npm install @modelcontextprotocol/sdk zod

This SDK has a required peer dependency on zod for schema validation. The SDK internally imports from zod/v4, but maintains backwards compatibility with projects using Zod v3.25 or later. You can use either API in your code by importing from zod/v3 or zod/v4:

Quick Start

To see the SDK in action end-to-end, start from the runnable examples in src/examples:

  1. Install dependencies (from the SDK repo root):

    npm install
    
  2. Run the example Streamable HTTP server:

    npx tsx src/examples/server/simpleStreamableHttp.ts
    
  3. Run the interactive client in another terminal:

    npx tsx src/examples/client/simpleStreamableHttp.ts
    

This pair of examples demonstrates tools, resources, prompts, sampling, elicitation, tasks and logging. For a guided walkthrough and variations (stateless servers, JSON-only responses, SSE compatibility, OAuth, etc.), see docs/server.md and docs/client.md.

Core Concepts

Servers and transports

An MCP server is typically created with McpServer and connected to a transport such as Streamable HTTP or stdio. The SDK supports:

  • Streamable HTTP for remote servers (recommended).
  • HTTP + SSE for backwards compatibility only.
  • stdio for local, process-spawned integrations.

Runnable server examples live under src/examples/server and are documented in docs/server.md.

Tools, resources, prompts

  • Tools let LLMs ask your server to take actions (computation, side effects, network calls).
  • Resources expose read-only data that clients can surface to users or models.
  • Prompts are reusable templates that help users talk to models in a consistent way.

The detailed APIs, including ResourceTemplate, completions, and display-name metadata, are covered in docs/server.md, with runnable implementations in simpleStreamableHttp.ts.

Capabilities: sampling, elicitation, and tasks

The SDK includes higher-level capabilities for richer workflows:

  • Sampling: server-side tools can ask connected clients to run LLM completions.
  • Form elicitation: tools can request non-sensitive input via structured forms.
  • URL elicitation: servers can ask users to complete secure flows in a browser (e.g., API key entry, payments, OAuth).
  • Tasks (experimental): long-running tool calls can be turned into tasks that you poll or resume later.

Conceptual overviews and links to runnable examples are in:

Key example servers include:

Clients

The high-level Client class connects to MCP servers over different transports and exposes helpers like listTools, callTool, listResources, readResource, listPrompts, and getPrompt.

Runnable clients live under src/examples/client and are described in docs/client.md, including:

Node.js Web Crypto (globalThis.crypto) compatibility

Some parts of the SDK (for example, JWT-based client authentication in auth-extensions.ts via jose) rely on the Web Crypto API exposed as globalThis.crypto.

See docs/faq.md for details on supported Node.js versions and how to polyfill globalThis.crypto when running on older Node.js runtimes.

Examples

The SDK ships runnable examples under src/examples. Use these tables to find the scenario you care about and jump straight to the corresponding code and docs.

Server examples

ScenarioDescriptionExample file(s)Related docs
Streamable HTTP server (stateful)Feature-rich server with tools, resources, prompts, logging, tasks, sampling, and optional OAuth.simpleStreamableHttp.tsserver.md, capabilities.md
Streamable HTTP server (stateless)No session tracking; good for simple API-style servers.simpleStatelessStreamableHttp.tsserver.md
JSON response mode (no SSE)Streamable HTTP with JSON responses only and limited notifications.jsonResponseStreamableHttp.tsserver.md
Server notifications over Streamable HTTPDemonstrates server-initiated notifications using SSE with Streamable HTTP.standaloneSseWithGetStreamableHttp.tsserver.md
Deprecated HTTP+SSE serverLegacy HTTP+SSE transport for backwards-compatibility testing.simpleSseServer.tsserver.md
Backwards-compatible server (Streamable HTTP + SSE)Single server that supports both Streamable HTTP and legacy SSE clients.sseAndStreamableHttpCompatibleServer.tsserver.md
Form elicitation serverUses form elicitation to collect non-sensitive user input.elicitationFormExample.tscapabilities.md
URL elicitation serverDemonstrates URL-mode elicitation in an OAuth-protected server.elicitationUrlExample.tscapabilities.md
Sampling and tasks serverCombines tools, logging, sampling, and experimental task-based execution.toolWithSampleServer.tscapabilities.md
OAuth demo authorization serverIn-memory OAuth provider used with the example servers.demoInMemoryOAuthProvider.tsserver.md

Client examples

ScenarioDescriptionExample file(s)Related docs
Interactive Streamable HTTP clientCLI client that exercises tools, resources, prompts, elicitation, and tasks.simpleStreamableHttp.tsclient.md
Backwards-compatible client (Streamable HTTP → SSE)Tries Streamable HTTP first, then falls back to SSE on 4xx responses.streamableHttpWithSseFallbackClient.tsclient.md, server.md
SSE polling clientPolls a legacy SSE server and demonstrates notification handling.ssePollingClient.tsclient.md
Parallel tool calls clientShows how to run multiple tool calls in parallel.parallelToolCallsClient.tsclient.md
Multiple clients in parallelDemonstrates connecting multiple clients concurrently to the same server.multipleClientsParallel.tsclient.md
OAuth clientsExamples of client_credentials (basic and private_key_jwt) and reusable providers.simpleOAuthClient.ts, simpleOAuthClientProvider.ts, simpleClientCredentials.tsclient.md
URL elicitation clientWorks with the URL elicitation server to drive secure browser flows.elicitationUrlExample.tscapabilities.md

Shared utilities:

For more details on how to run these examples (including recommended commands and deployment diagrams), see src/examples/README.md.

Documentation

Contributing

Issues and pull requests are welcome on GitHub at https://github.com/modelcontextprotocol/typescript-sdk.

License

This project is licensed under the MIT License—see the LICENSE file for details.