Update TypeScript examples to use simplified API

This commit is contained in:
Justin Spahr-Summers 2025-01-21 14:13:21 +00:00
commit 16b0cc8ccc
No known key found for this signature in database
4 changed files with 123 additions and 218 deletions

View file

@ -211,29 +211,24 @@ Here's a basic example of implementing an MCP server:
<Tabs> <Tabs>
<Tab title="TypeScript"> <Tab title="TypeScript">
```typescript ```typescript
import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.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: {}
}
}); });
// Handle requests // Register a resource
server.setRequestHandler(ListResourcesRequestSchema, async () => { server.resource(
return { "example",
resources: [ "example://resource",
{ async (uri) => ({
uri: "example://resource", contents: [{
name: "Example Resource" uri: uri.href,
} text: "Example resource content"
] }]
}; })
}); );
// Connect transport // Connect transport
const transport = new StdioServerTransport(); const transport = new StdioServerTransport();

View file

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

View file

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

View file

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