removed yaml from docs

This commit is contained in:
Ted Werbel 2025-03-01 14:59:48 -05:00
parent efa2799301
commit 3e31babf4f
2 changed files with 545 additions and 564 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,7 @@
---
description: When building MCP servers
globs: *.ts
---
# MCP TypeScript SDK ![NPM Version](mdc:https:/img.shields.io/npm/v/%40modelcontextprotocol%2Fsdk) ![MIT licensed](mdc:https:/img.shields.io/npm/l/%40modelcontextprotocol%2Fsdk) # MCP TypeScript SDK ![NPM Version](mdc:https:/img.shields.io/npm/v/%40modelcontextprotocol%2Fsdk) ![MIT licensed](mdc:https:/img.shields.io/npm/l/%40modelcontextprotocol%2Fsdk)
## Table of Contents ## Table of Contents
- [Overview](mdc:#overview) - [Overview](mdc:#overview)
- [Installation](mdc:#installation) - [Installation](mdc:#installation)
- [Quickstart](mdc:#quickstart) - [Quickstart](mdc:#quickstart)
@ -46,33 +43,35 @@ npm install @modelcontextprotocol/sdk
Let's create a simple MCP server that exposes a calculator tool and some data: Let's create a simple MCP server that exposes a calculator tool and some data:
```typescript ```typescript
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js"; import {
McpServer,
ResourceTemplate,
} from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod"; import { z } from "zod";
// Create an MCP server // Create an MCP server
const server = new McpServer({ const server = new McpServer({
name: "Demo", name: "Demo",
version: "1.0.0" version: "1.0.0",
}); });
// Add an addition tool // Add an addition tool
server.tool("add", server.tool("add", { a: z.number(), b: z.number() }, async ({ a, b }) => ({
{ a: z.number(), b: z.number() }, content: [{ type: "text", text: String(a + b) }],
async ({ a, b }) => ({ }));
content: [{ type: "text", text: String(a + b) }]
})
);
// Add a dynamic greeting resource // Add a dynamic greeting resource
server.resource( server.resource(
"greeting", "greeting",
new ResourceTemplate("greeting://{name}", { list: undefined }), new ResourceTemplate("greeting://{name}", { list: undefined }),
async (uri, { name }) => ({ async (uri, { name }) => ({
contents: [{ contents: [
uri: uri.href, {
text: `Hello, ${name}!` uri: uri.href,
}] text: `Hello, ${name}!`,
},
],
}) })
); );
@ -99,7 +98,7 @@ The McpServer is your core interface to the MCP protocol. It handles connection
```typescript ```typescript
const server = new McpServer({ const server = new McpServer({
name: "My App", name: "My App",
version: "1.0.0" version: "1.0.0",
}); });
``` ```
@ -109,26 +108,26 @@ Resources are how you expose data to LLMs. They're similar to GET endpoints in a
```typescript ```typescript
// Static resource // Static resource
server.resource( server.resource("config", "config://app", async (uri) => ({
"config", contents: [
"config://app", {
async (uri) => ({
contents: [{
uri: uri.href, uri: uri.href,
text: "App configuration here" text: "App configuration here",
}] },
}) ],
); }));
// Dynamic resource with parameters // Dynamic resource with parameters
server.resource( server.resource(
"user-profile", "user-profile",
new ResourceTemplate("users://{userId}/profile", { list: undefined }), new ResourceTemplate("users://{userId}/profile", { list: undefined }),
async (uri, { userId }) => ({ async (uri, { userId }) => ({
contents: [{ contents: [
uri: uri.href, {
text: `Profile data for user ${userId}` uri: uri.href,
}] text: `Profile data for user ${userId}`,
},
],
}) })
); );
``` ```
@ -143,28 +142,26 @@ server.tool(
"calculate-bmi", "calculate-bmi",
{ {
weightKg: z.number(), weightKg: z.number(),
heightM: z.number() heightM: z.number(),
}, },
async ({ weightKg, heightM }) => ({ async ({ weightKg, heightM }) => ({
content: [{ content: [
type: "text", {
text: String(weightKg / (heightM * heightM)) type: "text",
}] text: String(weightKg / (heightM * heightM)),
},
],
}) })
); );
// Async tool with external API call // Async tool with external API call
server.tool( server.tool("fetch-weather", { city: z.string() }, async ({ city }) => {
"fetch-weather", const response = await fetch(`https://api.weather.com/${city}`);
{ city: z.string() }, const data = await response.text();
async ({ city }) => { return {
const response = await fetch(`https://api.weather.com/${city}`); content: [{ type: "text", text: data }],
const data = await response.text(); };
return { });
content: [{ type: "text", text: data }]
};
}
);
``` ```
### Prompts ### Prompts
@ -172,19 +169,17 @@ server.tool(
Prompts are reusable templates that help LLMs interact with your server effectively: Prompts are reusable templates that help LLMs interact with your server effectively:
```typescript ```typescript
server.prompt( server.prompt("review-code", { code: z.string() }, ({ code }) => ({
"review-code", messages: [
{ code: z.string() }, {
({ code }) => ({
messages: [{
role: "user", role: "user",
content: { content: {
type: "text", type: "text",
text: `Please review this code:\n\n${code}` text: `Please review this code:\n\n${code}`,
} },
}] },
}) ],
); }));
``` ```
## Running Your Server ## Running Your Server
@ -201,7 +196,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
const server = new McpServer({ const server = new McpServer({
name: "example-server", name: "example-server",
version: "1.0.0" version: "1.0.0",
}); });
// ... set up server resources, tools, and prompts ... // ... set up server resources, tools, and prompts ...
@ -221,7 +216,7 @@ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
const server = new McpServer({ const server = new McpServer({
name: "example-server", name: "example-server",
version: "1.0.0" version: "1.0.0",
}); });
// ... set up server resources, tools, and prompts ... // ... set up server resources, tools, and prompts ...
@ -254,46 +249,45 @@ To test your server, you can use the [MCP Inspector](mdc:https:/github.com/model
A simple server demonstrating resources, tools, and prompts: A simple server demonstrating resources, tools, and prompts:
```typescript ```typescript
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js"; import {
McpServer,
ResourceTemplate,
} from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod"; import { z } from "zod";
const server = new McpServer({ const server = new McpServer({
name: "Echo", name: "Echo",
version: "1.0.0" version: "1.0.0",
}); });
server.resource( server.resource(
"echo", "echo",
new ResourceTemplate("echo://{message}", { list: undefined }), new ResourceTemplate("echo://{message}", { list: undefined }),
async (uri, { message }) => ({ async (uri, { message }) => ({
contents: [{ contents: [
uri: uri.href, {
text: `Resource echo: ${message}` uri: uri.href,
}] text: `Resource echo: ${message}`,
},
],
}) })
); );
server.tool( server.tool("echo", { message: z.string() }, async ({ message }) => ({
"echo", content: [{ type: "text", text: `Tool echo: ${message}` }],
{ message: z.string() }, }));
async ({ message }) => ({
content: [{ type: "text", text: `Tool echo: ${message}` }]
})
);
server.prompt( server.prompt("echo", { message: z.string() }, ({ message }) => ({
"echo", messages: [
{ message: z.string() }, {
({ message }) => ({
messages: [{
role: "user", role: "user",
content: { content: {
type: "text", type: "text",
text: `Please process this message: ${message}` text: `Please process this message: ${message}`,
} },
}] },
}) ],
); }));
``` ```
### SQLite Explorer ### SQLite Explorer
@ -308,7 +302,7 @@ import { z } from "zod";
const server = new McpServer({ const server = new McpServer({
name: "SQLite Explorer", name: "SQLite Explorer",
version: "1.0.0" version: "1.0.0",
}); });
// Helper to create DB connection // Helper to create DB connection
@ -316,58 +310,56 @@ const getDb = () => {
const db = new sqlite3.Database("database.db"); const db = new sqlite3.Database("database.db");
return { return {
all: promisify<string, any[]>(db.all.bind(db)), all: promisify<string, any[]>(db.all.bind(db)),
close: promisify(db.close.bind(db)) close: promisify(db.close.bind(db)),
}; };
}; };
server.resource( server.resource("schema", "schema://main", async (uri) => {
"schema", const db = getDb();
"schema://main", try {
async (uri) => { const tables = await db.all(
const db = getDb(); "SELECT sql FROM sqlite_master WHERE type='table'"
try { );
const tables = await db.all( return {
"SELECT sql FROM sqlite_master WHERE type='table'" contents: [
); {
return {
contents: [{
uri: uri.href, uri: uri.href,
text: tables.map((t: {sql: string}) => t.sql).join("\n") text: tables.map((t: { sql: string }) => t.sql).join("\n"),
}] },
}; ],
} finally { };
await db.close(); } finally {
} await db.close();
} }
); });
server.tool( server.tool("query", { sql: z.string() }, async ({ sql }) => {
"query", const db = getDb();
{ sql: z.string() }, try {
async ({ sql }) => { const results = await db.all(sql);
const db = getDb(); return {
try { content: [
const results = await db.all(sql); {
return {
content: [{
type: "text", type: "text",
text: JSON.stringify(results, null, 2) text: JSON.stringify(results, null, 2),
}] },
}; ],
} catch (err: unknown) { };
const error = err as Error; } catch (err: unknown) {
return { const error = err as Error;
content: [{ return {
content: [
{
type: "text", type: "text",
text: `Error: ${error.message}` text: `Error: ${error.message}`,
}], },
isError: true ],
}; isError: true,
} finally { };
await db.close(); } finally {
} await db.close();
} }
); });
``` ```
## Advanced Usage ## Advanced Usage
@ -381,32 +373,36 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { import {
ListPromptsRequestSchema, ListPromptsRequestSchema,
GetPromptRequestSchema GetPromptRequestSchema,
} from "@modelcontextprotocol/sdk/types.js"; } from "@modelcontextprotocol/sdk/types.js";
const server = new Server( const server = new Server(
{ {
name: "example-server", name: "example-server",
version: "1.0.0" version: "1.0.0",
}, },
{ {
capabilities: { capabilities: {
prompts: {} prompts: {},
} },
} }
); );
server.setRequestHandler(ListPromptsRequestSchema, async () => { server.setRequestHandler(ListPromptsRequestSchema, async () => {
return { return {
prompts: [{ prompts: [
name: "example-prompt", {
description: "An example prompt template", name: "example-prompt",
arguments: [{ description: "An example prompt template",
name: "arg1", arguments: [
description: "Example argument", {
required: true name: "arg1",
}] description: "Example argument",
}] required: true,
},
],
},
],
}; };
}); });
@ -416,13 +412,15 @@ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
} }
return { return {
description: "Example prompt", description: "Example prompt",
messages: [{ messages: [
role: "user", {
content: { role: "user",
type: "text", content: {
text: "Example prompt text" type: "text",
} text: "Example prompt text",
}] },
},
],
}; };
}); });
@ -440,20 +438,20 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
const transport = new StdioClientTransport({ const transport = new StdioClientTransport({
command: "node", command: "node",
args: ["server.js"] args: ["server.js"],
}); });
const client = new Client( const client = new Client(
{ {
name: "example-client", name: "example-client",
version: "1.0.0" version: "1.0.0",
}, },
{ {
capabilities: { capabilities: {
prompts: {}, prompts: {},
resources: {}, resources: {},
tools: {} tools: {},
} },
} }
); );
@ -464,7 +462,7 @@ const prompts = await client.listPrompts();
// Get a prompt // Get a prompt
const prompt = await client.getPrompt("example-prompt", { const prompt = await client.getPrompt("example-prompt", {
arg1: "value" arg1: "value",
}); });
// List resources // List resources
@ -477,8 +475,8 @@ const resource = await client.readResource("file:///example.txt");
const result = await client.callTool({ const result = await client.callTool({
name: "example-tool", name: "example-tool",
arguments: { arguments: {
arg1: "value" arg1: "value",
} },
}); });
``` ```
@ -494,4 +492,4 @@ Issues and pull requests are welcome on GitHub at https://github.com/modelcontex
## License ## License
This project is licensed under the MIT License—see the [LICENSE](mdc:LICENSE) file for details. This project is licensed under the MIT License—see the [LICENSE](mdc:LICENSE) file for details.