Skip to content

Commit eeda5d6

Browse files
committed
readme update
1 parent 37fc7d2 commit eeda5d6

File tree

6 files changed

+344
-338
lines changed

6 files changed

+344
-338
lines changed

README.md

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -312,19 +312,19 @@ For simpler use cases where session management isn't needed:
312312
const app = express();
313313
app.use(express.json());
314314

315-
const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({
316-
sessionIdGenerator: undefined, // set to undefined for stateless servers
317-
});
318-
319-
// Setup routes for the server
320-
const setupServer = async () => {
321-
await server.connect(transport);
322-
};
323-
324315
app.post('/mcp', async (req: Request, res: Response) => {
325-
console.log('Received MCP request:', req.body);
326316
try {
327-
await transport.handleRequest(req, res, req.body);
317+
const server = getServer();
318+
const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({
319+
sessionIdGenerator: undefined,
320+
});
321+
await server.connect(transport);
322+
await transport.handleRequest(req, res, req.body);
323+
res.on('close', () => {
324+
console.log('Request closed');
325+
transport.close();
326+
server.close();
327+
});
328328
} catch (error) {
329329
console.error('Error handling MCP request:', error);
330330
if (!res.headersSent) {
@@ -364,15 +364,11 @@ app.delete('/mcp', async (req: Request, res: Response) => {
364364
}));
365365
});
366366

367+
367368
// Start the server
368369
const PORT = 3000;
369-
setupServer().then(() => {
370-
app.listen(PORT, () => {
371-
console.log(`MCP Streamable HTTP Server listening on port ${PORT}`);
372-
});
373-
}).catch(error => {
374-
console.error('Failed to set up the server:', error);
375-
process.exit(1);
370+
app.listen(PORT, () => {
371+
console.log(`MCP Stateless Streamable HTTP Server listening on port ${PORT}`);
376372
});
377373

378374
```

src/examples/server/jsonResponseStreamableHttp.ts

Lines changed: 71 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -5,74 +5,78 @@ import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js';
55
import { z } from 'zod';
66
import { CallToolResult, isInitializeRequest } from '../../types.js';
77

8+
89
// Create an MCP server with implementation details
9-
const server = new McpServer({
10-
name: 'json-response-streamable-http-server',
11-
version: '1.0.0',
12-
}, {
13-
capabilities: {
14-
logging: {},
15-
}
16-
});
10+
const getServer = () => {
11+
const server = new McpServer({
12+
name: 'json-response-streamable-http-server',
13+
version: '1.0.0',
14+
}, {
15+
capabilities: {
16+
logging: {},
17+
}
18+
});
19+
20+
// Register a simple tool that returns a greeting
21+
server.tool(
22+
'greet',
23+
'A simple greeting tool',
24+
{
25+
name: z.string().describe('Name to greet'),
26+
},
27+
async ({ name }): Promise<CallToolResult> => {
28+
return {
29+
content: [
30+
{
31+
type: 'text',
32+
text: `Hello, ${name}!`,
33+
},
34+
],
35+
};
36+
}
37+
);
38+
39+
// Register a tool that sends multiple greetings with notifications
40+
server.tool(
41+
'multi-greet',
42+
'A tool that sends different greetings with delays between them',
43+
{
44+
name: z.string().describe('Name to greet'),
45+
},
46+
async ({ name }, { sendNotification }): Promise<CallToolResult> => {
47+
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
48+
49+
await sendNotification({
50+
method: "notifications/message",
51+
params: { level: "debug", data: `Starting multi-greet for ${name}` }
52+
});
1753

18-
// Register a simple tool that returns a greeting
19-
server.tool(
20-
'greet',
21-
'A simple greeting tool',
22-
{
23-
name: z.string().describe('Name to greet'),
24-
},
25-
async ({ name }): Promise<CallToolResult> => {
26-
return {
27-
content: [
28-
{
29-
type: 'text',
30-
text: `Hello, ${name}!`,
31-
},
32-
],
33-
};
34-
}
35-
);
36-
37-
// Register a tool that sends multiple greetings with notifications
38-
server.tool(
39-
'multi-greet',
40-
'A tool that sends different greetings with delays between them',
41-
{
42-
name: z.string().describe('Name to greet'),
43-
},
44-
async ({ name }, { sendNotification }): Promise<CallToolResult> => {
45-
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
46-
47-
await sendNotification({
48-
method: "notifications/message",
49-
params: { level: "debug", data: `Starting multi-greet for ${name}` }
50-
});
51-
52-
await sleep(1000); // Wait 1 second before first greeting
53-
54-
await sendNotification({
55-
method: "notifications/message",
56-
params: { level: "info", data: `Sending first greeting to ${name}` }
57-
});
58-
59-
await sleep(1000); // Wait another second before second greeting
60-
61-
await sendNotification({
62-
method: "notifications/message",
63-
params: { level: "info", data: `Sending second greeting to ${name}` }
64-
});
65-
66-
return {
67-
content: [
68-
{
69-
type: 'text',
70-
text: `Good morning, ${name}!`,
71-
}
72-
],
73-
};
74-
}
75-
);
54+
await sleep(1000); // Wait 1 second before first greeting
55+
56+
await sendNotification({
57+
method: "notifications/message",
58+
params: { level: "info", data: `Sending first greeting to ${name}` }
59+
});
60+
61+
await sleep(1000); // Wait another second before second greeting
62+
63+
await sendNotification({
64+
method: "notifications/message",
65+
params: { level: "info", data: `Sending second greeting to ${name}` }
66+
});
67+
68+
return {
69+
content: [
70+
{
71+
type: 'text',
72+
text: `Good morning, ${name}!`,
73+
}
74+
],
75+
};
76+
}
77+
);
78+
return server;
79+
}
7680

7781
const app = express();
7882
app.use(express.json());
@@ -104,6 +108,7 @@ app.post('/mcp', async (req: Request, res: Response) => {
104108
});
105109

106110
// Connect the transport to the MCP server BEFORE handling the request
111+
const server = getServer();
107112
await server.connect(transport);
108113
await transport.handleRequest(req, res, req.body);
109114
return; // Already handled
@@ -153,6 +158,5 @@ app.listen(PORT, () => {
153158
// Handle server shutdown
154159
process.on('SIGINT', async () => {
155160
console.log('Shutting down server...');
156-
await server.close();
157161
process.exit(0);
158162
});

src/examples/server/simpleSseServer.ts

Lines changed: 55 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -15,60 +15,63 @@ import { CallToolResult } from '../../types.js';
1515
*/
1616

1717
// Create an MCP server instance
18-
const server = new McpServer({
19-
name: 'simple-sse-server',
20-
version: '1.0.0',
21-
}, { capabilities: { logging: {} } });
22-
23-
server.tool(
24-
'start-notification-stream',
25-
'Starts sending periodic notifications',
26-
{
27-
interval: z.number().describe('Interval in milliseconds between notifications').default(1000),
28-
count: z.number().describe('Number of notifications to send').default(10),
29-
},
30-
async ({ interval, count }, { sendNotification }): Promise<CallToolResult> => {
31-
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
32-
let counter = 0;
33-
34-
// Send the initial notification
35-
await sendNotification({
36-
method: "notifications/message",
37-
params: {
38-
level: "info",
39-
data: `Starting notification stream with ${count} messages every ${interval}ms`
18+
const getServer = () => {
19+
const server = new McpServer({
20+
name: 'simple-sse-server',
21+
version: '1.0.0',
22+
}, { capabilities: { logging: {} } });
23+
24+
server.tool(
25+
'start-notification-stream',
26+
'Starts sending periodic notifications',
27+
{
28+
interval: z.number().describe('Interval in milliseconds between notifications').default(1000),
29+
count: z.number().describe('Number of notifications to send').default(10),
30+
},
31+
async ({ interval, count }, { sendNotification }): Promise<CallToolResult> => {
32+
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
33+
let counter = 0;
34+
35+
// Send the initial notification
36+
await sendNotification({
37+
method: "notifications/message",
38+
params: {
39+
level: "info",
40+
data: `Starting notification stream with ${count} messages every ${interval}ms`
41+
}
42+
});
43+
44+
// Send periodic notifications
45+
while (counter < count) {
46+
counter++;
47+
await sleep(interval);
48+
49+
try {
50+
await sendNotification({
51+
method: "notifications/message",
52+
params: {
53+
level: "info",
54+
data: `Notification #${counter} at ${new Date().toISOString()}`
55+
}
56+
});
57+
}
58+
catch (error) {
59+
console.error("Error sending notification:", error);
60+
}
4061
}
41-
});
42-
43-
// Send periodic notifications
44-
while (counter < count) {
45-
counter++;
46-
await sleep(interval);
47-
48-
try {
49-
await sendNotification({
50-
method: "notifications/message",
51-
params: {
52-
level: "info",
53-
data: `Notification #${counter} at ${new Date().toISOString()}`
62+
63+
return {
64+
content: [
65+
{
66+
type: 'text',
67+
text: `Completed sending ${count} notifications every ${interval}ms`,
5468
}
55-
});
56-
}
57-
catch (error) {
58-
console.error("Error sending notification:", error);
59-
}
69+
],
70+
};
6071
}
61-
62-
return {
63-
content: [
64-
{
65-
type: 'text',
66-
text: `Completed sending ${count} notifications every ${interval}ms`,
67-
}
68-
],
69-
};
70-
}
71-
);
72+
);
73+
return server;
74+
};
7275

7376
const app = express();
7477
app.use(express.json());
@@ -96,6 +99,7 @@ app.get('/mcp', async (req: Request, res: Response) => {
9699
};
97100

98101
// Connect the transport to the MCP server
102+
const server = getServer();
99103
await server.connect(transport);
100104

101105
// Start the SSE transport to begin streaming
@@ -163,7 +167,6 @@ process.on('SIGINT', async () => {
163167
console.error(`Error closing transport for session ${sessionId}:`, error);
164168
}
165169
}
166-
await server.close();
167170
console.log('Server shutdown complete');
168171
process.exit(0);
169172
});

src/examples/server/simpleStatelessStreamableHttp.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,6 @@ const getServer = () => {
9696
const app = express();
9797
app.use(express.json());
9898

99-
100-
101-
10299
app.post('/mcp', async (req: Request, res: Response) => {
103100
const server = getServer();
104101
try {

0 commit comments

Comments
 (0)