-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathmcp-server.js
More file actions
executable file
·290 lines (255 loc) · 9.31 KB
/
mcp-server.js
File metadata and controls
executable file
·290 lines (255 loc) · 9.31 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env node
/*
Copyright 2025 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
// Support SSE for backward compatibility
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
// Support stdio, as it is easier to use locally
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { registerTools, registerToolsRemote } from './tools/tools.js';
import { SetLevelRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { registerPrompts } from './prompts.js';
import { checkGCP } from './lib/cloud-api/metadata.js';
import { ensureGCPCredentials } from './lib/cloud-api/auth.js';
import { extractAccessToken } from './lib/util/helpers.js';
import { oauthMiddleware } from './lib/middleware/oauth.js';
import { config } from '@dotenvx/dotenvx';
import {
SCOPES,
GCLOUD_AUTH,
BEARER_METHODS_SUPPORTED,
RESPONSE_TYPES_SUPPORTED,
} from './constants.js';
//Suppress the warning related to missing .env file in case of non-OAuth mode
config({ quiet: true, ignore: ['MISSING_ENV_FILE'] });
const gcpInfo = await checkGCP();
let gcpCredentialsAvailable = false;
/**
* Ensure that console.log and console.error are compatible with stdio.
* (Right now, it just disables them)
*/
function makeLoggingCompatibleWithStdio() {
// redirect all console.log (which usually go to to stdout) to stderr.
console.log = console.error;
}
function shouldStartStdio() {
if (process.env.GCP_STDIO === 'false' || (gcpInfo && gcpInfo.project)) {
return false;
}
return true;
}
if (shouldStartStdio()) {
makeLoggingCompatibleWithStdio();
}
// Read default configurations from environment variables
const envProjectId = process.env.GOOGLE_CLOUD_PROJECT || undefined;
const envRegion = process.env.GOOGLE_CLOUD_REGION;
const defaultServiceName = process.env.DEFAULT_SERVICE_NAME;
const skipIamCheck = process.env.SKIP_IAM_CHECK !== 'false';
// Values for RUN_INGRESS_POLICY could be: "INGRESS_TRAFFIC_ALL", "INGRESS_TRAFFIC_INTERNAL_ONLY", "INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER"
const ingress = process.env.RUN_INGRESS_POLICY || undefined;
const enableHostValidation = process.env.ENABLE_HOST_VALIDATION === 'true';
const allowedHosts = process.env.ALLOWED_HOSTS
? process.env.ALLOWED_HOSTS.split(',')
: undefined;
async function getServer(accessToken = GCLOUD_AUTH) {
// Create an MCP server with implementation details
const server = new McpServer(
{
name: 'cloud-run',
version: '1.0.0',
},
{ capabilities: { logging: {} } }
);
// this is no-op handler is required for mcp-inspector to function due to a mismatch between the SDK mcp-inspector
server.server.setRequestHandler(SetLevelRequestSchema, (request) => {
console.log(`Log Level: ${request.params.level}`);
return {};
});
// Get GCP metadata info once
const gcpInfo = await checkGCP();
// Determine the effective project and region based on priority: Env Var > GCP Metadata > Hardcoded default
const effectiveProjectId =
envProjectId || (gcpInfo && gcpInfo.project) || undefined;
const effectiveRegion =
envRegion || (gcpInfo && gcpInfo.region) || 'europe-west1';
if (shouldStartStdio() || !(gcpInfo && gcpInfo.project)) {
console.log('Using tools optimized for local or stdio mode.');
// Pass the determined defaults to the local tool registration
await registerTools(server, {
defaultProjectId: effectiveProjectId,
defaultRegion: effectiveRegion,
defaultServiceName,
skipIamCheck,
ingress,
gcpCredentialsAvailable,
accessToken,
});
} else {
console.log(
`Running on GCP project: ${effectiveProjectId}, region: ${effectiveRegion}. Using tools optimized for remote use.`
);
// Pass the determined defaults to the remote tool registration
await registerToolsRemote(server, {
defaultProjectId: effectiveProjectId,
defaultRegion: effectiveRegion,
defaultServiceName,
skipIamCheck,
ingress,
gcpCredentialsAvailable,
accessToken,
});
}
// Register prompts with the server
registerPrompts(server);
return server;
}
const getOAuthProtectedResource = (req, res) => {
res.json({
resource: process.env.OAUTH_PROTECTED_RESOURCE,
authorization_servers: [process.env.OAUTH_AUTHORIZATION_SERVER],
scopes_supported: [SCOPES.OPENID, SCOPES.EMAIL, SCOPES.CLOUD_PLATFORM],
bearer_methods_supported: [...BEARER_METHODS_SUPPORTED],
});
res.status(200).send();
};
const getOAuthAuthorizationServer = (req, res) => {
res.json({
issuer: process.env.OAUTH_PROTECTED_RESOURCE,
authorization_endpoint: process.env.OAUTH_AUTHORIZATION_ENDPOINT,
token_endpoint: process.env.OAUTH_TOKEN_ENDPOINT,
scopes_supported: [SCOPES.OPENID, SCOPES.EMAIL, SCOPES.CLOUD_PLATFORM],
response_types_supported: [...RESPONSE_TYPES_SUPPORTED],
});
res.status(200).send();
};
// stdio mode
if (shouldStartStdio()) {
gcpCredentialsAvailable = await ensureGCPCredentials();
const stdioTransport = new StdioServerTransport();
const server = await getServer();
await server.connect(stdioTransport);
console.log('Cloud Run MCP server stdio transport connected');
} else {
// non-stdio mode
console.log('Stdio transport mode is turned off.');
gcpCredentialsAvailable =
process.env.OAUTH_ENABLED === 'true' || (await ensureGCPCredentials());
const app = enableHostValidation
? createMcpExpressApp({ allowedHosts })
: createMcpExpressApp({ host: null });
if (!enableHostValidation) {
console.warn(
`Warning: Server is running without DNS rebinding protection. ` +
'Consider enabling host validation by passing env variable ENABLE_HOST_VALIDATION=true and adding the ALLOWED_HOSTS to restrict allowed hosts'
);
}
app.get('/.well-known/oauth-protected-resource', getOAuthProtectedResource);
app.get(
'/.well-known/oauth-authorization-server',
getOAuthAuthorizationServer
);
app.post('/mcp', oauthMiddleware, async (req, res) => {
console.log('/mcp Received:', req.body);
const accessToken = extractAccessToken(req.headers.authorization);
const server = await getServer(accessToken);
try {
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
});
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
res.on('close', () => {
console.log('Request closed');
transport.close();
server.close();
});
} catch (error) {
console.error('Error handling MCP request:', error);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: '2.0',
error: {
code: -32603,
message: 'Internal server error',
},
id: null,
});
}
}
});
app.get('/mcp', async (req, res) => {
console.log('Received GET MCP request');
res.writeHead(405).end(
JSON.stringify({
jsonrpc: '2.0',
error: {
code: -32000,
message: 'Method not allowed.',
},
id: null,
})
);
});
app.delete('/mcp', async (req, res) => {
console.log('Received DELETE MCP request');
res.writeHead(405).end(
JSON.stringify({
jsonrpc: '2.0',
error: {
code: -32000,
message: 'Method not allowed.',
},
id: null,
})
);
});
// Support SSE for baackward compatibility
const sseTransports = {};
// Legacy SSE endpoint for older clients
app.get('/sse', async (req, res) => {
console.log('/sse Received:', req.body);
const accessToken = extractAccessToken(req.headers.authorization);
const server = await getServer(accessToken);
// Create SSE transport for legacy clients
const transport = new SSEServerTransport('/messages', res);
sseTransports[transport.sessionId] = transport;
res.on('close', () => {
delete sseTransports[transport.sessionId];
});
await server.connect(transport);
});
// Legacy message endpoint for older clients
app.post('/messages', async (req, res) => {
console.log('/messages Received:', req.body);
const sessionId = req.query.sessionId;
const transport = sseTransports[sessionId];
if (transport) {
await transport.handlePostMessage(req, res, req.body);
} else {
res.status(400).send('No transport found for sessionId');
}
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Cloud Run MCP server listening on port ${PORT}`);
});
}
// Handle server shutdown
process.on('SIGINT', async () => {
console.log('Shutting down server...');
process.exit(0);
});