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)
## Table of Contents
- [Overview](mdc:#overview)
- [Installation](mdc:#installation)
- [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:
```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 { z } from "zod";
// Create an MCP server
const server = new McpServer({
name: "Demo",
version: "1.0.0"
version: "1.0.0",
});
// Add an addition tool
server.tool("add",
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }]
})
);
server.tool("add", { a: z.number(), b: z.number() }, async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }],
}));
// Add a dynamic greeting resource
server.resource(
"greeting",
new ResourceTemplate("greeting://{name}", { list: undefined }),
async (uri, { name }) => ({
contents: [{
uri: uri.href,
text: `Hello, ${name}!`
}]
contents: [
{
uri: uri.href,
text: `Hello, ${name}!`,
},
],
})
);
@ -99,7 +98,7 @@ The McpServer is your core interface to the MCP protocol. It handles connection
```typescript
const server = new McpServer({
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
// Static resource
server.resource(
"config",
"config://app",
async (uri) => ({
contents: [{
server.resource("config", "config://app", async (uri) => ({
contents: [
{
uri: uri.href,
text: "App configuration here"
}]
})
);
text: "App configuration here",
},
],
}));
// Dynamic resource with parameters
server.resource(
"user-profile",
new ResourceTemplate("users://{userId}/profile", { list: undefined }),
async (uri, { userId }) => ({
contents: [{
uri: uri.href,
text: `Profile data for user ${userId}`
}]
contents: [
{
uri: uri.href,
text: `Profile data for user ${userId}`,
},
],
})
);
```
@ -143,28 +142,26 @@ server.tool(
"calculate-bmi",
{
weightKg: z.number(),
heightM: z.number()
heightM: z.number(),
},
async ({ weightKg, heightM }) => ({
content: [{
type: "text",
text: String(weightKg / (heightM * heightM))
}]
content: [
{
type: "text",
text: String(weightKg / (heightM * heightM)),
},
],
})
);
// Async tool with external API call
server.tool(
"fetch-weather",
{ city: z.string() },
async ({ city }) => {
const response = await fetch(`https://api.weather.com/${city}`);
const data = await response.text();
return {
content: [{ type: "text", text: data }]
};
}
);
server.tool("fetch-weather", { city: z.string() }, async ({ city }) => {
const response = await fetch(`https://api.weather.com/${city}`);
const data = await response.text();
return {
content: [{ type: "text", text: data }],
};
});
```
### Prompts
@ -172,19 +169,17 @@ server.tool(
Prompts are reusable templates that help LLMs interact with your server effectively:
```typescript
server.prompt(
"review-code",
{ code: z.string() },
({ code }) => ({
messages: [{
server.prompt("review-code", { code: z.string() }, ({ code }) => ({
messages: [
{
role: "user",
content: {
type: "text",
text: `Please review this code:\n\n${code}`
}
}]
})
);
text: `Please review this code:\n\n${code}`,
},
},
],
}));
```
## Running Your Server
@ -201,7 +196,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
const server = new McpServer({
name: "example-server",
version: "1.0.0"
version: "1.0.0",
});
// ... set up server resources, tools, and prompts ...
@ -221,7 +216,7 @@ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
const server = new McpServer({
name: "example-server",
version: "1.0.0"
version: "1.0.0",
});
// ... 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:
```typescript
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
McpServer,
ResourceTemplate,
} from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const server = new McpServer({
name: "Echo",
version: "1.0.0"
version: "1.0.0",
});
server.resource(
"echo",
new ResourceTemplate("echo://{message}", { list: undefined }),
async (uri, { message }) => ({
contents: [{
uri: uri.href,
text: `Resource echo: ${message}`
}]
contents: [
{
uri: uri.href,
text: `Resource echo: ${message}`,
},
],
})
);
server.tool(
"echo",
{ message: z.string() },
async ({ message }) => ({
content: [{ type: "text", text: `Tool echo: ${message}` }]
})
);
server.tool("echo", { message: z.string() }, async ({ message }) => ({
content: [{ type: "text", text: `Tool echo: ${message}` }],
}));
server.prompt(
"echo",
{ message: z.string() },
({ message }) => ({
messages: [{
server.prompt("echo", { message: z.string() }, ({ message }) => ({
messages: [
{
role: "user",
content: {
type: "text",
text: `Please process this message: ${message}`
}
}]
})
);
text: `Please process this message: ${message}`,
},
},
],
}));
```
### SQLite Explorer
@ -308,7 +302,7 @@ import { z } from "zod";
const server = new McpServer({
name: "SQLite Explorer",
version: "1.0.0"
version: "1.0.0",
});
// Helper to create DB connection
@ -316,58 +310,56 @@ const getDb = () => {
const db = new sqlite3.Database("database.db");
return {
all: promisify<string, any[]>(db.all.bind(db)),
close: promisify(db.close.bind(db))
close: promisify(db.close.bind(db)),
};
};
server.resource(
"schema",
"schema://main",
async (uri) => {
const db = getDb();
try {
const tables = await db.all(
"SELECT sql FROM sqlite_master WHERE type='table'"
);
return {
contents: [{
server.resource("schema", "schema://main", async (uri) => {
const db = getDb();
try {
const tables = await db.all(
"SELECT sql FROM sqlite_master WHERE type='table'"
);
return {
contents: [
{
uri: uri.href,
text: tables.map((t: {sql: string}) => t.sql).join("\n")
}]
};
} finally {
await db.close();
}
text: tables.map((t: { sql: string }) => t.sql).join("\n"),
},
],
};
} finally {
await db.close();
}
);
});
server.tool(
"query",
{ sql: z.string() },
async ({ sql }) => {
const db = getDb();
try {
const results = await db.all(sql);
return {
content: [{
server.tool("query", { sql: z.string() }, async ({ sql }) => {
const db = getDb();
try {
const results = await db.all(sql);
return {
content: [
{
type: "text",
text: JSON.stringify(results, null, 2)
}]
};
} catch (err: unknown) {
const error = err as Error;
return {
content: [{
text: JSON.stringify(results, null, 2),
},
],
};
} catch (err: unknown) {
const error = err as Error;
return {
content: [
{
type: "text",
text: `Error: ${error.message}`
}],
isError: true
};
} finally {
await db.close();
}
text: `Error: ${error.message}`,
},
],
isError: true,
};
} finally {
await db.close();
}
);
});
```
## Advanced Usage
@ -381,32 +373,36 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
ListPromptsRequestSchema,
GetPromptRequestSchema
GetPromptRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
const server = new Server(
{
name: "example-server",
version: "1.0.0"
version: "1.0.0",
},
{
capabilities: {
prompts: {}
}
prompts: {},
},
}
);
server.setRequestHandler(ListPromptsRequestSchema, async () => {
return {
prompts: [{
name: "example-prompt",
description: "An example prompt template",
arguments: [{
name: "arg1",
description: "Example argument",
required: true
}]
}]
prompts: [
{
name: "example-prompt",
description: "An example prompt template",
arguments: [
{
name: "arg1",
description: "Example argument",
required: true,
},
],
},
],
};
});
@ -416,13 +412,15 @@ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
}
return {
description: "Example prompt",
messages: [{
role: "user",
content: {
type: "text",
text: "Example prompt text"
}
}]
messages: [
{
role: "user",
content: {
type: "text",
text: "Example prompt text",
},
},
],
};
});
@ -440,20 +438,20 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
const transport = new StdioClientTransport({
command: "node",
args: ["server.js"]
args: ["server.js"],
});
const client = new Client(
{
name: "example-client",
version: "1.0.0"
version: "1.0.0",
},
{
capabilities: {
prompts: {},
resources: {},
tools: {}
}
tools: {},
},
}
);
@ -464,7 +462,7 @@ const prompts = await client.listPrompts();
// Get a prompt
const prompt = await client.getPrompt("example-prompt", {
arg1: "value"
arg1: "value",
});
// List resources
@ -477,8 +475,8 @@ const resource = await client.readResource("file:///example.txt");
const result = await client.callTool({
name: "example-tool",
arguments: {
arg1: "value"
}
arg1: "value",
},
});
```
@ -494,4 +492,4 @@ Issues and pull requests are welcome on GitHub at https://github.com/modelcontex
## 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.