Repository navigation
Expand file tree
/
Copy pathhttp.js
More file actions
151 lines (134 loc) · 4.36 KB
/
Copy pathhttp.js
File metadata and controls
151 lines (134 loc) · 4.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import { createServer } from 'node:http'
import { randomUUID } from 'node:crypto'
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js'
const log = (...a) => console.error('[stochastic-thinking:http]', ...a)
const CORS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, mcp-session-id, Accept',
'Access-Control-Expose-Headers': 'mcp-session-id'
}
function json (res, status, body) {
res.writeHead(status, { ...CORS, 'Content-Type': 'application/json' })
res.end(JSON.stringify(body))
}
function readBody (req) {
return new Promise((resolve, reject) => {
const chunks = []
req.on('data', (c) => chunks.push(c))
req.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString()))
} catch (e) {
reject(e)
}
})
req.on('error', reject)
})
}
export async function startHttpTransport (server, port) {
const host = process.env.HTTP_HOST || 'localhost'
port = port ?? (Number(process.env.HTTP_PORT) || 3778)
const transports = new Map()
const httpServer = createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`)
const path = url.pathname
if (req.method === 'OPTIONS') {
res.writeHead(204, CORS)
res.end()
return
}
if (path === '/health' && req.method === 'GET') {
json(res, 200, { status: 'ok', server: 'stochastic-thinking-server', version: '0.1.0' })
return
}
if (path !== '/mcp') {
json(res, 404, { error: 'Not found' })
return
}
try {
if (req.method === 'POST') {
const body = await readBody(req)
const sessionId = req.headers['mcp-session-id']
let transport
if (sessionId && transports.has(sessionId)) {
transport = transports.get(sessionId)
} else if (!sessionId && isInitializeRequest(body)) {
log('new session')
transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (id) => {
log('session initialized:', id)
transports.set(id, transport)
}
})
transport.onclose = () => {
const id = transport.sessionId
if (id) {
transports.delete(id)
log('session closed:', id)
}
}
await server.connect(transport)
} else {
json(res, 400, {
jsonrpc: '2.0',
error: { code: -32000, message: 'Bad Request: no valid session' },
id: null
})
return
}
await transport.handleRequest(req, res, body)
return
}
if (req.method === 'GET') {
const sessionId = req.headers['mcp-session-id']
if (sessionId && transports.has(sessionId)) {
await transports.get(sessionId).handleRequest(req, res)
return
}
json(res, 400, {
jsonrpc: '2.0',
error: { code: -32000, message: 'Bad Request: no valid session' },
id: null
})
return
}
if (req.method === 'DELETE') {
const sessionId = req.headers['mcp-session-id']
if (sessionId && transports.has(sessionId)) {
const transport = transports.get(sessionId)
await transport.handleRequest(req, res)
transports.delete(sessionId)
log('session deleted:', sessionId)
return
}
json(res, 400, {
jsonrpc: '2.0',
error: { code: -32000, message: 'Bad Request: no valid session' },
id: null
})
return
}
res.writeHead(405, { ...CORS, Allow: 'GET, POST, DELETE, OPTIONS' })
res.end('Method Not Allowed')
} catch (err) {
log('error:', err.message)
if (!res.headersSent) {
json(res, 500, {
jsonrpc: '2.0',
error: { code: -32603, message: 'Internal server error' },
id: null
})
}
}
})
return new Promise((resolve, reject) => {
httpServer.listen(port, host, () => {
log(`listening on http://${host}:${port}/mcp`)
resolve(httpServer)
})
httpServer.on('error', reject)
})
}