Your cart is currently empty!
MCP: Low Level Tools with Javascript SDK
Install:
pnpm add @modelcontextprotocol/sdk
Create server.js
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
ListToolsRequestSchema,
CallToolRequestSchema
} from "@modelcontextprotocol/sdk/types.js";
// Create an MCP server
const server = new Server(
{
name: "demo-server",
version: "1.0.0"
},
{
capabilities: {
tools: {}
}
});
tools/list
// tools/list
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "calculate_sum",
description: "Calculates the sum of two numbers.",
inputSchema: {
type: "object",
properties: {
num1: { type: "number" },
num2: { type: "number" },
},
required: ["num1", "num2"],
},
},
// Add more tool definitions as needed
],
};
});tools/call (part 1)
// tools/call
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "calculate_sum") {
const { num1, num2 } = request.params.arguments;
const sum = num1 + num2;
return {
abc: "def"
};
}
});
// start the server
const transport = new StdioServerTransport();
await server.connect(transport);try it out
node client.js
{
"content": [],
"abc": "def"
}try it out with cli:
echo '{"jsonrpc":"2.0","method":"tools/call", "params": {"name":"calculate_sum", "arguments": {"num1": 1, "num2": 2}},"id":1}' | node server.js | jq{
"result": {
"abc": "def"
},
"jsonrpc": "2.0",
"id": 1
}tools/call (part 2)
// tools/call
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "calculate_sum") {
const { num1, num2 } = request.params.arguments;
const sum = num1 + num2;
return {
content: [
{
type: "text",
text: "hello"
},
{
type: "resource_link",
uri: "hello://world",
name: "hello-world"
},
{
type: "resource",
resource: {
uri: "hello://world",
text: "hello world",
mimeType: "plain/text"
}
},
]
};
}
});
// start the server
const transport = new StdioServerTransport();
await server.connect(transport);try it out
node client.js
{
"content": [
{
"type": "text",
"text": "hello"
},
{
"name": "hello-world",
"uri": "hello://world",
"type": "resource_link"
},
{
"type": "resource",
"resource": {
"uri": "hello://world",
"mimeType": "plain/text",
"text": "hello world"
}
}
]
}try it out with cli:
echo '{"jsonrpc":"2.0","method":"tools/call", "params": {"name":"calculate_sum", "arguments": {"num1": 1, "num2": 2}},"id":1}' | node server.js | jq{
"result": {
"content": [
{
"type": "text",
"text": "hello"
},
{
"type": "resource_link",
"uri": "hello://world",
"name": "hello-world"
},
{
"type": "resource",
"resource": {
"uri": "hello://world",
"text": "hello world",
"mimeType": "plain/text"
}
}
]
},
"jsonrpc": "2.0",
"id": 1
}References:

Leave a Reply