Merge pull request #118 from modelcontextprotocol/revert-115-justin/simplified-ts-sdk

Revert "Update TypeScript examples to use simplified API"
This commit is contained in:
Justin Spahr-Summers 2025-01-23 14:01:33 +00:00 • committed by GitHub
commit 3684fe2ddd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 251 additions and 141 deletions

View file

@ -210,30 +210,35 @@ Here's a basic example of implementing an MCP server:
<Tabs> <Tabs>
<Tab title="TypeScript"> <Tab title="TypeScript">
```typescript ```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new McpServer({ const server = new Server({
name: "example-server", name: "example-server",
version: "1.0.0" version: "1.0.0"
}); }, {
capabilities: {
resources: {}
}
});
// Register a resource // Handle requests
server.resource( server.setRequestHandler(ListResourcesRequestSchema, async () => {
"example", return {
"example://resource", resources: [
async (uri) => ({ {
contents: [{ uri: "example://resource",
uri: uri.href, name: "Example Resource"
text: "Example resource content" }
}] ]
}) };
); });
// Connect transport // Connect transport
const transport = new StdioServerTransport(); const transport = new StdioServerTransport();
await server.connect(transport); await server.connect(transport);
``` ```
</Tab> </Tab>
<Tab title="Python"> <Tab title="Python">
```python ```python

View file

@ -197,52 +197,98 @@ Here's a complete example of implementing prompts in an MCP server:
<Tabs> <Tabs>
<Tab title="TypeScript"> <Tab title="TypeScript">
```typescript ```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { Server } from "@modelcontextprotocol/sdk/server";
import { z } from "zod"; import {
ListPromptsRequestSchema,
GetPromptRequestSchema
} from "@modelcontextprotocol/sdk/types";
const server = new McpServer({ const PROMPTS = {
name: "example-prompts-server", "git-commit": {
version: "1.0.0" name: "git-commit",
}); description: "Generate a Git commit message",
arguments: [
{
name: "changes",
description: "Git diff or description of changes",
required: true
}
]
},
"explain-code": {
name: "explain-code",
description: "Explain how code works",
arguments: [
{
name: "code",
description: "Code to explain",
required: true
},
{
name: "language",
description: "Programming language",
required: false
}
]
}
};
// Register git commit prompt const server = new Server({
server.prompt( name: "example-prompts-server",
"git-commit", version: "1.0.0"
"Generate a Git commit message", }, {
{ capabilities: {
changes: z.string().describe("Git diff or description of changes") prompts: {}
}, }
({ changes }) => ({ });
messages: [{
role: "user",
content: {
type: "text",
text: `Generate a concise but descriptive commit message for these changes:\n\n${changes}`
}
}]
})
);
// Register code explanation prompt // List available prompts
server.prompt( server.setRequestHandler(ListPromptsRequestSchema, async () => {
"explain-code", return {
"Explain how code works", prompts: Object.values(PROMPTS)
{ };
code: z.string().describe("Code to explain"), });
language: z.string().optional().describe("Programming language")
}, // Get specific prompt
({ code, language }) => ({ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
messages: [{ const prompt = PROMPTS[request.params.name];
role: "user", if (!prompt) {
content: { throw new Error(`Prompt not found: ${request.params.name}`);
type: "text", }
text: `Explain how this ${language || "Unknown"} code works:\n\n${code}`
} if (request.params.name === "git-commit") {
}] return {
}) messages: [
); {
``` role: "user",
content: {
type: "text",
text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}`
}
}
]
};
}
if (request.params.name === "explain-code") {
const language = request.params.arguments?.language || "Unknown";
return {
messages: [
{
role: "user",
content: {
type: "text",
text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}`
}
}
]
};
}
throw new Error("Prompt implementation not found");
});
```
</Tab> </Tab>
<Tab title="Python"> <Tab title="Python">
```python ```python

View file

@ -145,32 +145,47 @@ Here's a simple example of implementing resource support in an MCP server:
<Tabs> <Tabs>
<Tab title="TypeScript"> <Tab title="TypeScript">
```typescript ```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; const server = new Server({
const server = new McpServer({
name: "example-server", name: "example-server",
version: "1.0.0" version: "1.0.0"
}, {
capabilities: {
resources: {}
}
}); });
// Add static resource // List available resources
server.resource( server.setRequestHandler(ListResourcesRequestSchema, async () => {
"logs", return {
"file:///logs/app.log", resources: [
{ {
mimeType: "text/plain", uri: "file:///logs/app.log",
description: "Application log file" name: "Application Logs",
}, mimeType: "text/plain"
async (uri) => { }
]
};
});
// Read resource contents
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const uri = request.params.uri;
if (uri === "file:///logs/app.log") {
const logContents = await readLogFile(); const logContents = await readLogFile();
return { return {
contents: [{ contents: [
uri: uri.href, {
mimeType: "text/plain", uri,
text: logContents mimeType: "text/plain",
}] text: logContents
}
]
}; };
} }
);
throw new Error("Resource not found");
});
``` ```
</Tab> </Tab>
<Tab title="Python"> <Tab title="Python">

View file

@ -40,31 +40,50 @@ Here's an example of implementing a basic tool in an MCP server:
<Tabs> <Tabs>
<Tab title="TypeScript"> <Tab title="TypeScript">
```typescript ```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; const server = new Server({
import { z } from "zod"; name: "example-server",
version: "1.0.0"
}, {
capabilities: {
tools: {}
}
});
const server = new McpServer({ // Define available tools
name: "example-server", server.setRequestHandler(ListToolsRequestSchema, async () => {
version: "1.0.0" return {
}); tools: [{
name: "calculate_sum",
description: "Add two numbers together",
inputSchema: {
type: "object",
properties: {
a: { type: "number" },
b: { type: "number" }
},
required: ["a", "b"]
}
}]
};
});
// Register a tool // Handle tool execution
server.tool( server.setRequestHandler(CallToolRequestSchema, async (request) => {
"calculate_sum", if (request.params.name === "calculate_sum") {
"Add two numbers together", const { a, b } = request.params.arguments;
{ return {
a: z.number(), content: [
b: z.number() {
}, type: "text",
async ({ a, b }) => ({ text: String(a + b)
content: [{ }
type: "text", ]
text: String(a + b) };
}] }
}) throw new Error("Tool not found");
); });
``` ```
</Tab> </Tab>
<Tab title="Python"> <Tab title="Python">
```python ```python

View file

@ -450,39 +450,64 @@ const ForecastArgumentsSchema = z.object({
longitude: z.number().min(-180).max(180), longitude: z.number().min(-180).max(180),
}); });
// Create server instance
const server = new Server(
{
name: "weather",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
```
### Implementing tool listing
We need to tell clients what tools are available. This `server.setRequestHandler` call will register this list for us:
```typescript ```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; // List available tools
import { z } from "zod"; server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
const server = new McpServer({ tools: [
name: "weather", {
version: "1.0.0" name: "get-alerts",
description: "Get weather alerts for a state",
inputSchema: {
type: "object",
properties: {
state: {
type: "string",
description: "Two-letter state code (e.g. CA, NY)",
},
},
required: ["state"],
},
},
{
name: "get-forecast",
description: "Get weather forecast for a location",
inputSchema: {
type: "object",
properties: {
latitude: {
type: "number",
description: "Latitude of the location",
},
longitude: {
type: "number",
description: "Longitude of the location",
},
},
required: ["latitude", "longitude"],
},
},
],
};
}); });
// Register weather alert tool
server.tool(
"get-alerts",
"Get weather alerts for a state",
{
state: z.string().length(2).describe("Two-letter state code (e.g. CA, NY)")
},
async ({ state }) => {
// Tool implementation
}
);
// Register forecast tool
server.tool(
"get-forecast",
"Get weather forecast for a location",
{
latitude: z.number().min(-90).max(90).describe("Latitude of the location"),
longitude: z.number().min(-180).max(180).describe("Longitude of the location")
},
async ({ latitude, longitude }) => {
// Tool implementation
}
);
``` ```
This defines our two tools: `get-alerts` and `get-forecast`. This defines our two tools: `get-alerts` and `get-forecast`.