conductor-node-mcp 14.24.4 → 15.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/agent-errors.d.mts +3 -0
- package/agent-errors.d.mts.map +1 -0
- package/agent-errors.d.ts +3 -0
- package/agent-errors.d.ts.map +1 -0
- package/agent-errors.js +97 -0
- package/agent-errors.js.map +1 -0
- package/agent-errors.mjs +93 -0
- package/agent-errors.mjs.map +1 -0
- package/code-tool-worker.d.mts.map +1 -1
- package/code-tool-worker.d.ts.map +1 -1
- package/code-tool-worker.js +3 -0
- package/code-tool-worker.js.map +1 -1
- package/code-tool-worker.mjs +3 -0
- package/code-tool-worker.mjs.map +1 -1
- package/code-tool.d.mts.map +1 -1
- package/code-tool.d.ts.map +1 -1
- package/code-tool.js +73 -14
- package/code-tool.js.map +1 -1
- package/code-tool.mjs +73 -14
- package/code-tool.mjs.map +1 -1
- package/http.d.mts.map +1 -1
- package/http.d.ts.map +1 -1
- package/http.js +38 -22
- package/http.js.map +1 -1
- package/http.mjs +37 -21
- package/http.mjs.map +1 -1
- package/local-docs-search.js +3 -3
- package/local-docs-search.js.map +1 -1
- package/local-docs-search.mjs +3 -3
- package/local-docs-search.mjs.map +1 -1
- package/oauth.d.mts +26 -0
- package/oauth.d.mts.map +1 -0
- package/oauth.d.ts +26 -0
- package/oauth.d.ts.map +1 -0
- package/oauth.js +446 -0
- package/oauth.js.map +1 -0
- package/oauth.mjs +433 -0
- package/oauth.mjs.map +1 -0
- package/package.json +32 -2
- package/server.d.mts +2 -1
- package/server.d.mts.map +1 -1
- package/server.d.ts +2 -1
- package/server.d.ts.map +1 -1
- package/server.js +7 -3
- package/server.js.map +1 -1
- package/server.mjs +7 -3
- package/server.mjs.map +1 -1
- package/src/agent-errors.ts +98 -0
- package/src/code-tool-worker.ts +3 -0
- package/src/code-tool.ts +78 -18
- package/src/http.ts +35 -30
- package/src/local-docs-search.ts +3 -3
- package/src/oauth.ts +540 -0
- package/src/server.ts +8 -3
- package/src/telemetry.ts +110 -0
- package/src/types.ts +4 -0
- package/telemetry.d.mts +18 -0
- package/telemetry.d.mts.map +1 -0
- package/telemetry.d.ts +18 -0
- package/telemetry.d.ts.map +1 -0
- package/telemetry.js +105 -0
- package/telemetry.js.map +1 -0
- package/telemetry.mjs +96 -0
- package/telemetry.mjs.map +1 -0
- package/types.d.mts +2 -0
- package/types.d.mts.map +1 -1
- package/types.d.ts +2 -0
- package/types.d.ts.map +1 -1
- package/types.js.map +1 -1
- package/types.mjs.map +1 -1
package/src/oauth.ts
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
// Conductor patch: OAuth 2.1 resource-server behavior for the hosted MCP server
|
|
2
|
+
// (https://mcp.conductor.is/, its /mcp alias, and its read-only connector URL https://mcp.conductor.is/read-only). Claude, ChatGPT and other OAuth-capable MCP
|
|
3
|
+
// clients start sign-in only when a credential-less POST answers HTTP 401 with
|
|
4
|
+
// a WWW-Authenticate header that names this server's protected resource
|
|
5
|
+
// metadata (RFC 9728), which points at the authorization server (the
|
|
6
|
+
// dashboard). The server stays stateless and holds no secret: credentials pass
|
|
7
|
+
// through unchanged and the only validation is an upstream probe of the API on
|
|
8
|
+
// tools/call, which treats a key as dead only when the API's own JSON error
|
|
9
|
+
// envelope says so (api.conductor.is sits behind Cloudflare; an edge 401/403
|
|
10
|
+
// page must fail open). Every gate decision and every probe is logged as one
|
|
11
|
+
// structured line because http.ts redacts www-authenticate from Render logs.
|
|
12
|
+
// The URLs are hardcoded: every customer's connector stores them, so they
|
|
13
|
+
// never change. The rest of the config is read from non-MCP_SERVER_ env names
|
|
14
|
+
// (see code-tool.ts for why) with production defaults baked in.
|
|
15
|
+
import cors from 'cors';
|
|
16
|
+
import { createHash } from 'node:crypto';
|
|
17
|
+
import express from 'express';
|
|
18
|
+
import { getLogger } from './logger';
|
|
19
|
+
import { sdkMethods } from './methods';
|
|
20
|
+
import { rpcMethodProps, sanitizeUserAgent } from './telemetry';
|
|
21
|
+
import { readEnv } from './util';
|
|
22
|
+
|
|
23
|
+
// A local end-to-end run edits these two temporarily (see the dashboard's src/lib/oauth/README.md).
|
|
24
|
+
const AUTHORIZATION_SERVER_URL = 'https://dashboard.conductor.is';
|
|
25
|
+
const RESOURCE_URL = 'https://mcp.conductor.is/';
|
|
26
|
+
const DEFAULT_API_BASE_URL = 'https://api.conductor.is/v1'; // conductor-node's own default (src/client.ts)
|
|
27
|
+
const PROTECTED_RESOURCE_METADATA_PATH = '/.well-known/oauth-protected-resource';
|
|
28
|
+
// The read-only connector URL. POST /read-only (Express also matches /read-only/) allows only reads (see
|
|
29
|
+
// forceReadOnlyPermissions; a guardrail, not a security boundary). Its identifier is
|
|
30
|
+
// `${origin}/read-only` with no trailing slash (hosted Claude strips one from a connector URL, and SDK 1.x
|
|
31
|
+
// clients refuse a metadata resource longer than the URL the user typed), and its RFC 9728 document sits at
|
|
32
|
+
// PROTECTED_RESOURCE_METADATA_PATH + READ_ONLY_PATH, which is what path insertion produces for it.
|
|
33
|
+
const READ_ONLY_PATH = '/read-only';
|
|
34
|
+
const KEY_PROBE_TIMEOUT_MS = 3000;
|
|
35
|
+
const KEY_PROBE_PATH = '/end-users/end_usr_oauth_probe'; // auth: "secret" route; 404 with a live key, 401 with a dead one
|
|
36
|
+
// The only codes apps/server emits as a 401/403 on the probe route for a presented non-empty Bearer key
|
|
37
|
+
// (context/auth-context.ts, services/api-key-service.ts, the SECRET_KEY_REQUIRED 403 for a publishable key).
|
|
38
|
+
// PAID_PLAN_REQUIRED applies only to QBD requests and HTTPS_REQUIRED only to http in production; neither reaches this route.
|
|
39
|
+
const KEY_PROBE_REJECTION_CODES: ReadonlySet<string> = new Set(['API_KEY_INVALID', 'SECRET_KEY_REQUIRED']);
|
|
40
|
+
// A fixed, distinct User-Agent so the probe can be filtered by UA as well as by path (end_usr_oauth_probe) in Better Stack.
|
|
41
|
+
const KEY_PROBE_USER_AGENT = 'conductor-mcp-key-probe/1';
|
|
42
|
+
// Only tools/call is probed. initialize, tools/list, notifications and server/discover never contact the API, so the
|
|
43
|
+
// Betterstack initialize monitor keeps a dummy Bearer and connection checks stay instant. The guard test pins this line.
|
|
44
|
+
const PROBED_METHODS: ReadonlySet<string> = new Set(['tools/call']);
|
|
45
|
+
// search_docs never contacts the API, so a call to it alone is not probed.
|
|
46
|
+
const UNPROBED_TOOLS: ReadonlySet<string> = new Set(['search_docs']);
|
|
47
|
+
// A 'valid' verdict is reused for this long per key (keyed by its SHA-256, never the key), so a busy session
|
|
48
|
+
// pays one probe a minute instead of one per call. A key deleted in the dashboard keeps working here for up
|
|
49
|
+
// to a minute; 'invalid' and 'unknown' are never cached.
|
|
50
|
+
const VALID_KEY_CACHE_TTL_MS = 60_000;
|
|
51
|
+
const VALID_KEY_CACHE_MAX_ENTRIES = 10_000;
|
|
52
|
+
const validKeyCache = new Map<string, number>(); // sha256(token) -> expiry, insertion-ordered
|
|
53
|
+
// Parallel calls with the same uncached key share one probe.
|
|
54
|
+
const inFlightProbes = new Map<string, Promise<KeyProbeResult>>();
|
|
55
|
+
|
|
56
|
+
export type OAuthResource = 'root' | 'read-only';
|
|
57
|
+
|
|
58
|
+
export interface OAuthResourceConfig {
|
|
59
|
+
authorizationServerUrl: string; // no trailing slash
|
|
60
|
+
resourceUrl: string; // root: RESOURCE_URL, trailing slash kept; read-only: `${origin}/read-only`, no slash
|
|
61
|
+
resourceMetadataUrl: string; // `${origin}/.well-known/oauth-protected-resource`, plus READ_ONLY_PATH for read-only
|
|
62
|
+
apiBaseUrl: string; // no trailing slash
|
|
63
|
+
keyProbeEnabled: boolean;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
type Credential =
|
|
67
|
+
| { kind: 'bearer' | 'header'; token: string }
|
|
68
|
+
| { kind: 'missing' }
|
|
69
|
+
| { kind: 'invalid'; header: 'authorization' | 'x-conductor-secret-key'; shape: CredentialShape };
|
|
70
|
+
// What was wrong with a rejected credential, logged on the gate line so a wrong-scheme connector can be
|
|
71
|
+
// diagnosed without any part of the value: an empty Bearer, a recognizable scheme word (basic, token,
|
|
72
|
+
// apikey, ...), a pasted header line, with a colon in or after its first word (scheme:colon), a value that
|
|
73
|
+
// starts with a quote mark (scheme:quoted), some other first word, no space at all (a bare key pasted
|
|
74
|
+
// without the Bearer word, which is told apart only by its public sk_conductor_ prefix), or an empty custom
|
|
75
|
+
// header.
|
|
76
|
+
export type CredentialShape =
|
|
77
|
+
| 'empty_bearer'
|
|
78
|
+
| `scheme:${string}`
|
|
79
|
+
| 'no_scheme:sk_conductor_'
|
|
80
|
+
| 'no_scheme:other'
|
|
81
|
+
| 'empty_custom_header';
|
|
82
|
+
type GateRejection = 'missing' | 'invalid_scheme' | 'dead_key';
|
|
83
|
+
type WwwAuthenticateError = 'invalid_token';
|
|
84
|
+
type KeyProbeVerdict = 'valid' | 'invalid' | 'unknown';
|
|
85
|
+
// code: the API's rejection code, for an 'invalid' verdict only.
|
|
86
|
+
type KeyProbeResult = { verdict: KeyProbeVerdict; code?: string; error?: string };
|
|
87
|
+
|
|
88
|
+
// Read per call (cheap), so tests set process.env between requests and http.ts's signature does not change.
|
|
89
|
+
// The read-only resource is derived from the root.
|
|
90
|
+
export function getOAuthResourceConfig(resource: OAuthResource = 'root'): OAuthResourceConfig {
|
|
91
|
+
const isReadOnly = resource === 'read-only';
|
|
92
|
+
// Absolute paths resolved against the root, so the identifier and the path-inserted RFC 9728 metadata URL
|
|
93
|
+
// both come from READ_ONLY_PATH; http.ts's '/read-only' route literals must match it (the seal test pins them).
|
|
94
|
+
return {
|
|
95
|
+
authorizationServerUrl: AUTHORIZATION_SERVER_URL,
|
|
96
|
+
resourceUrl: isReadOnly ? new URL(READ_ONLY_PATH, RESOURCE_URL).href : RESOURCE_URL,
|
|
97
|
+
resourceMetadataUrl: new URL(
|
|
98
|
+
PROTECTED_RESOURCE_METADATA_PATH + (isReadOnly ? READ_ONLY_PATH : ''),
|
|
99
|
+
RESOURCE_URL,
|
|
100
|
+
).href,
|
|
101
|
+
apiBaseUrl: (readEnv('CONDUCTOR_BASE_URL') ?? DEFAULT_API_BASE_URL).replace(/\/+$/, ''),
|
|
102
|
+
keyProbeEnabled: !['off', 'false', '0', 'no'].includes(
|
|
103
|
+
(readEnv('CONDUCTOR_MCP_KEY_PROBE') ?? '').trim().toLowerCase(),
|
|
104
|
+
),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// No scopes_supported: read-only is decided by the URL the client POSTs to, never by the token, and listing
|
|
109
|
+
// none keeps Claude from requesting offline_access (a refresh token this server never issues).
|
|
110
|
+
export function buildProtectedResourceMetadata(config: OAuthResourceConfig): Record<string, unknown> {
|
|
111
|
+
return {
|
|
112
|
+
resource: config.resourceUrl,
|
|
113
|
+
authorization_servers: [config.authorizationServerUrl],
|
|
114
|
+
bearer_methods_supported: ['header'],
|
|
115
|
+
resource_name: 'Conductor MCP server',
|
|
116
|
+
resource_documentation: 'https://docs.conductor.is/usage/mcp',
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function mountProtectedResourceMetadata(app: express.Express): void {
|
|
121
|
+
// Preflight gets Access-Control-Allow-Origin: *. Each literal path also matches its trailing-slash form
|
|
122
|
+
// (strict routing is off), so the read-only document answers under the well-known prefix whether a client
|
|
123
|
+
// follows the 401 hint (no slash) or builds the path itself from the URL the user typed. No splat route:
|
|
124
|
+
// any other suffix is a 404.
|
|
125
|
+
for (const resource of ['root', 'read-only'] as const) {
|
|
126
|
+
const path = PROTECTED_RESOURCE_METADATA_PATH + (resource === 'read-only' ? READ_ONLY_PATH : '');
|
|
127
|
+
app.options(path, cors());
|
|
128
|
+
app.get(path, cors(), (_req, res) => {
|
|
129
|
+
res
|
|
130
|
+
.status(200)
|
|
131
|
+
.set('Cache-Control', 'public, max-age=300')
|
|
132
|
+
.json(buildProtectedResourceMetadata(getOAuthResourceConfig(resource)));
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Descriptions are fixed ASCII strings with no double quotes. For a MISSING credential no error
|
|
138
|
+
// param is sent (RFC 6750 3.1), so the challenge is just the resource_metadata pointer and the
|
|
139
|
+
// description appears only in the JSON body.
|
|
140
|
+
export function buildWwwAuthenticate(
|
|
141
|
+
config: OAuthResourceConfig,
|
|
142
|
+
error?: WwwAuthenticateError,
|
|
143
|
+
description?: string,
|
|
144
|
+
): string {
|
|
145
|
+
const params: string[] = [];
|
|
146
|
+
if (error !== undefined) {
|
|
147
|
+
params.push(`error="${error}"`);
|
|
148
|
+
if (description !== undefined) params.push(`error_description="${description}"`);
|
|
149
|
+
}
|
|
150
|
+
params.push(`resource_metadata="${config.resourceMetadataUrl}"`);
|
|
151
|
+
return `Bearer ${params.join(', ')}`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Runs after express.json() (so req.body.method is readable) and before post(). A credential-less
|
|
155
|
+
// POST with invalid JSON is a 400 from the body parser, as today; real clients never send one.
|
|
156
|
+
// On the read-only route the gate also rewrites the client permissions header before http.ts parses it.
|
|
157
|
+
export function requireCredential(resource: OAuthResource = 'root'): express.RequestHandler {
|
|
158
|
+
return async (req, res, next) => {
|
|
159
|
+
const config = getOAuthResourceConfig(resource);
|
|
160
|
+
const credential = extractCredential(req);
|
|
161
|
+
// Set by http.ts's session middleware (the request's own header or a fresh UUID), so the gate and probe
|
|
162
|
+
// lines join pino-http's request line even on a first-contact 401 that carried no mcp-session-id.
|
|
163
|
+
const mcpSessionId = (req as any).mcpSessionId as string | undefined;
|
|
164
|
+
if (credential.kind === 'missing') {
|
|
165
|
+
return reject(
|
|
166
|
+
req,
|
|
167
|
+
res,
|
|
168
|
+
config,
|
|
169
|
+
resource,
|
|
170
|
+
'missing',
|
|
171
|
+
undefined,
|
|
172
|
+
'Sign in to Conductor, or send your Conductor secret key in the Authorization header',
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
if (credential.kind === 'invalid') {
|
|
176
|
+
return reject(
|
|
177
|
+
req,
|
|
178
|
+
res,
|
|
179
|
+
config,
|
|
180
|
+
resource,
|
|
181
|
+
'invalid_scheme',
|
|
182
|
+
'invalid_token',
|
|
183
|
+
credential.header === 'x-conductor-secret-key' ?
|
|
184
|
+
'The x-conductor-secret-key header is empty. Set it to your Conductor secret key'
|
|
185
|
+
: 'The Authorization header must be the word Bearer, a space, and your Conductor secret key',
|
|
186
|
+
credential.shape,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
canonicalizeCredential(req, credential);
|
|
190
|
+
if (resource === 'read-only') forceReadOnlyPermissions(req);
|
|
191
|
+
if (config.keyProbeEnabled && bodyHasProbedMethod(req.body)) {
|
|
192
|
+
const probe = await probeKeyCached(credential.token, config, mcpSessionId); // never throws
|
|
193
|
+
if (probe.verdict === 'invalid') {
|
|
194
|
+
return reject(
|
|
195
|
+
req,
|
|
196
|
+
res,
|
|
197
|
+
config,
|
|
198
|
+
resource,
|
|
199
|
+
'dead_key',
|
|
200
|
+
'invalid_token',
|
|
201
|
+
probe.code === 'SECRET_KEY_REQUIRED' ?
|
|
202
|
+
'This is a Conductor publishable key. Use a secret key instead'
|
|
203
|
+
: 'This Conductor key is invalid or was deleted. Sign in again, or create a new key on the MCP tab in the Conductor Dashboard',
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
next();
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// The log line is load-bearing: http.ts's redactHeaders (/auth|cookie|key|token|x-stainless-mcp-client-envs/i,
|
|
212
|
+
// applied to RESPONSE headers too) writes www-authenticate as [REDACTED] and pino-http logs no body, so
|
|
213
|
+
// without it a first-contact 401 (expected), a wrong-scheme 401 (the misconfigured customer behind the
|
|
214
|
+
// 130-per-48h 500s) and a dead-key 401 are identical in Render logs. The body is advisory; Claude and the
|
|
215
|
+
// SDK clients read only the status and the header. The line also carries the credential's shape (never
|
|
216
|
+
// any part of its value), the JSON-RPC method, the client's User-Agent and the resource, so a keyless
|
|
217
|
+
// retry loop, a wrong-scheme connector and a first-contact sign-in are told apart without a join.
|
|
218
|
+
function reject(
|
|
219
|
+
req: express.Request,
|
|
220
|
+
res: express.Response,
|
|
221
|
+
config: OAuthResourceConfig,
|
|
222
|
+
resource: OAuthResource,
|
|
223
|
+
gate: GateRejection,
|
|
224
|
+
error: WwwAuthenticateError | undefined,
|
|
225
|
+
description: string,
|
|
226
|
+
credentialShape?: CredentialShape,
|
|
227
|
+
): void {
|
|
228
|
+
getLogger().warn(
|
|
229
|
+
{
|
|
230
|
+
mcpSessionId: (req as any).mcpSessionId,
|
|
231
|
+
oauthGate: gate,
|
|
232
|
+
...(credentialShape !== undefined && { credentialShape }),
|
|
233
|
+
...rpcMethodProps(req.body),
|
|
234
|
+
userAgent: sanitizeUserAgent(req.headers['user-agent'], 100),
|
|
235
|
+
resource,
|
|
236
|
+
},
|
|
237
|
+
'OAuth gate rejected request',
|
|
238
|
+
);
|
|
239
|
+
res
|
|
240
|
+
.status(401)
|
|
241
|
+
.set('WWW-Authenticate', buildWwwAuthenticate(config, error, description))
|
|
242
|
+
.set('Cache-Control', 'no-store')
|
|
243
|
+
.json({ error: error ?? 'invalid_token', error_description: description });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Precedence mirrors parseClientAuthHeaders (Authorization wins) so what the gate accepts is exactly what
|
|
247
|
+
// newServer uses. x-conductor-secret-key is always a string in Express: Node joins duplicate custom request
|
|
248
|
+
// headers with a comma and only set-cookie is an array; narrowed with typeof for the TypeScript type.
|
|
249
|
+
function extractCredential(req: express.Request): Credential {
|
|
250
|
+
const authorization = req.headers.authorization;
|
|
251
|
+
// Truthy, like parseClientAuthHeaders: an empty Authorization header falls through to the custom header.
|
|
252
|
+
if (authorization) {
|
|
253
|
+
const { scheme, token } = splitAuthorization(authorization);
|
|
254
|
+
if (scheme.toLowerCase() === 'bearer' && token !== '') return { kind: 'bearer', token };
|
|
255
|
+
// Basic, Digest, 'Bearer' alone, 'Bearer ', a bare key
|
|
256
|
+
return { kind: 'invalid', header: 'authorization', shape: authorizationShape(authorization) };
|
|
257
|
+
}
|
|
258
|
+
const headerKey = req.headers['x-conductor-secret-key'];
|
|
259
|
+
if (typeof headerKey === 'string') {
|
|
260
|
+
const token = headerKey.trim();
|
|
261
|
+
return token === '' ?
|
|
262
|
+
{ kind: 'invalid', header: 'x-conductor-secret-key', shape: 'empty_custom_header' }
|
|
263
|
+
: { kind: 'header', token };
|
|
264
|
+
}
|
|
265
|
+
return { kind: 'missing' };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// The one place an Authorization value is split: the first word and the trimmed rest (empty when there
|
|
269
|
+
// is no space), shared by the gate and the shape label so the two never disagree.
|
|
270
|
+
function splitAuthorization(authorization: string): { scheme: string; token: string; hasSpace: boolean } {
|
|
271
|
+
const spaceIndex = authorization.indexOf(' ');
|
|
272
|
+
if (spaceIndex === -1) return { scheme: authorization, token: '', hasSpace: false };
|
|
273
|
+
return {
|
|
274
|
+
scheme: authorization.slice(0, spaceIndex),
|
|
275
|
+
token: authorization.slice(spaceIndex + 1).trim(),
|
|
276
|
+
hasSpace: true,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// The shape of an Authorization value that is not `Bearer <key>`. Exported for its unit test; the value
|
|
281
|
+
// itself is never returned or logged. A scheme word is logged only when it is short and alphabetic, so a
|
|
282
|
+
// pasted secret can never become the label.
|
|
283
|
+
export function authorizationShape(authorization: string): CredentialShape {
|
|
284
|
+
const { scheme, hasSpace } = splitAuthorization(authorization);
|
|
285
|
+
if (scheme.toLowerCase() === 'bearer') return 'empty_bearer'; // 'Bearer' alone, 'Bearer ', 'bearer '
|
|
286
|
+
// The two paste mistakes a header-name-plus-value dialog invites (Copilot Studio's read-only connection,
|
|
287
|
+
// 2026-11-05, eight scheme:other rejections): a header line ("Authorization: Bearer x", "Bearer: x",
|
|
288
|
+
// "Bearer:x", '"Authorization": "Bearer x"') or a quoted value ('"Bearer x"').
|
|
289
|
+
if (!hasSpace) {
|
|
290
|
+
if (authorization.startsWith('sk_conductor_')) return 'no_scheme:sk_conductor_';
|
|
291
|
+
return authorization.includes(':') ? 'scheme:colon' : 'no_scheme:other';
|
|
292
|
+
}
|
|
293
|
+
if (/^[A-Za-z]{1,12}$/.test(scheme)) return `scheme:${scheme.toLowerCase()}`;
|
|
294
|
+
if (scheme.includes(':')) return 'scheme:colon';
|
|
295
|
+
if (authorization.startsWith('"') || authorization.startsWith("'")) return 'scheme:quoted';
|
|
296
|
+
return 'scheme:other';
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// The generated parseClientAuthHeaders switches on the literal 'Bearer' and throws otherwise, so the
|
|
300
|
+
// header is rewritten in canonical form ('bearer'/'BEARER' and 'Bearer x' with two spaces all become
|
|
301
|
+
// 'Bearer x'); the custom header is replaced by its trimmed value.
|
|
302
|
+
function canonicalizeCredential(
|
|
303
|
+
req: express.Request,
|
|
304
|
+
credential: { kind: 'bearer' | 'header'; token: string },
|
|
305
|
+
): void {
|
|
306
|
+
if (credential.kind === 'bearer') {
|
|
307
|
+
req.headers.authorization = `Bearer ${credential.token}`;
|
|
308
|
+
} else {
|
|
309
|
+
req.headers['x-conductor-secret-key'] = credential.token;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// The read-only connector URL allows the client's own permissions minus every write: the HTTP GET methods,
|
|
314
|
+
// or only the GETs among a client's allowed_methods when it sent that list without allow_http_gets:true, less
|
|
315
|
+
// its blocked_methods. The header is REWRITTEN, not merged: http.ts spreads whatever it parses over
|
|
316
|
+
// mcpOptions, so a client {"allow_http_gets":false} would restore full access and an allowed_methods regexp
|
|
317
|
+
// would union writes back in; allowed_methods is therefore replaced by the exact names of the GETs it matches.
|
|
318
|
+
// A server started with its own --code-allowed-methods would still union those in; the hosted service sets
|
|
319
|
+
// none. A malformed value is left as sent, so http.ts refuses it with the same 400 as on the root.
|
|
320
|
+
function forceReadOnlyPermissions(req: express.Request): void {
|
|
321
|
+
const sent = req.headers['x-stainless-mcp-client-permissions'];
|
|
322
|
+
const client = typeof sent === 'string' ? parseClientPermissions(sent) : {};
|
|
323
|
+
if (client === null) return;
|
|
324
|
+
const forced: ClientPermissions = { allow_http_gets: true };
|
|
325
|
+
if (client.allowed_methods !== undefined && client.allow_http_gets !== true) {
|
|
326
|
+
const allowed = client.allowed_methods.map((pattern) => new RegExp(pattern));
|
|
327
|
+
forced.allow_http_gets = false;
|
|
328
|
+
forced.allowed_methods = sdkMethods
|
|
329
|
+
.filter(
|
|
330
|
+
(method) =>
|
|
331
|
+
method.httpMethod === 'get' && allowed.some((regexp) => regexp.test(method.fullyQualifiedName)),
|
|
332
|
+
)
|
|
333
|
+
.map((method) => `^${method.fullyQualifiedName.replace(/\./g, '\\.')}$`); // names are dotted identifiers
|
|
334
|
+
}
|
|
335
|
+
if (client.blocked_methods !== undefined) forced.blocked_methods = client.blocked_methods;
|
|
336
|
+
req.headers['x-stainless-mcp-client-permissions'] = JSON.stringify(forced);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export type ClientPermissions = {
|
|
340
|
+
allow_http_gets?: boolean;
|
|
341
|
+
allowed_methods?: string[];
|
|
342
|
+
blocked_methods?: string[];
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
// The one parser for x-stainless-mcp-client-permissions, shared by http.ts and the read-only gate so both
|
|
346
|
+
// paths refuse the same values. Returns null unless the header is a JSON object holding only known keys of
|
|
347
|
+
// the right types with valid regexps, so a typo such as {"allow_http_gets":"true"} or {"read_only":true} is
|
|
348
|
+
// refused instead of ignored, and a bad pattern is a 400 instead of a 500 from the method filter.
|
|
349
|
+
export function parseClientPermissions(header: string): ClientPermissions | null {
|
|
350
|
+
let parsed: unknown;
|
|
351
|
+
try {
|
|
352
|
+
parsed = JSON.parse(header);
|
|
353
|
+
} catch {
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
const isPatternArray = (value: unknown) =>
|
|
360
|
+
Array.isArray(value) && value.every((item) => typeof item === 'string' && isValidRegExp(item));
|
|
361
|
+
const isValid = Object.entries(parsed).every(([key, value]) =>
|
|
362
|
+
key === 'allow_http_gets' ? typeof value === 'boolean'
|
|
363
|
+
: key === 'allowed_methods' || key === 'blocked_methods' ? isPatternArray(value)
|
|
364
|
+
: false,
|
|
365
|
+
);
|
|
366
|
+
return isValid ? (parsed as ClientPermissions) : null;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function isValidRegExp(pattern: string): boolean {
|
|
370
|
+
try {
|
|
371
|
+
new RegExp(pattern);
|
|
372
|
+
return true;
|
|
373
|
+
} catch {
|
|
374
|
+
return false;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// body is an object with a string `method` in PROBED_METHODS, or an array with any such element (JSON-RPC
|
|
379
|
+
// batch), and the call is not only to a tool in UNPROBED_TOOLS.
|
|
380
|
+
function bodyHasProbedMethod(body: unknown): boolean {
|
|
381
|
+
const messages: unknown[] = Array.isArray(body) ? body : [body];
|
|
382
|
+
return messages.some((message) => {
|
|
383
|
+
if (typeof message !== 'object' || message === null) return false;
|
|
384
|
+
const { method, params } = message as { method?: unknown; params?: { name?: unknown } };
|
|
385
|
+
if (typeof method !== 'string' || !PROBED_METHODS.has(method)) return false;
|
|
386
|
+
const toolName = typeof params === 'object' && params !== null ? params.name : undefined;
|
|
387
|
+
return !(typeof toolName === 'string' && UNPROBED_TOOLS.has(toolName));
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async function probeKeyCached(
|
|
392
|
+
token: string,
|
|
393
|
+
config: OAuthResourceConfig,
|
|
394
|
+
mcpSessionId: string | undefined,
|
|
395
|
+
): Promise<KeyProbeResult> {
|
|
396
|
+
const cacheKey = createHash('sha256').update(token).digest('hex');
|
|
397
|
+
const expiresAt = validKeyCache.get(cacheKey);
|
|
398
|
+
if (expiresAt !== undefined && expiresAt > Date.now()) return { verdict: 'valid' };
|
|
399
|
+
validKeyCache.delete(cacheKey);
|
|
400
|
+
const pending = inFlightProbes.get(cacheKey);
|
|
401
|
+
if (pending !== undefined) {
|
|
402
|
+
// One line under this session too, so its gate line has a probe result next to it.
|
|
403
|
+
const shared = await pending;
|
|
404
|
+
getLogger()[shared.verdict === 'unknown' ? 'warn' : 'info'](
|
|
405
|
+
{ mcpSessionId, keyProbe: { ...shared, shared: true } },
|
|
406
|
+
'key probe',
|
|
407
|
+
);
|
|
408
|
+
return shared;
|
|
409
|
+
}
|
|
410
|
+
const probe = probeKey(token, config, mcpSessionId).finally(() => inFlightProbes.delete(cacheKey));
|
|
411
|
+
inFlightProbes.set(cacheKey, probe);
|
|
412
|
+
const result = await probe;
|
|
413
|
+
if (result.verdict === 'valid') {
|
|
414
|
+
if (validKeyCache.size >= VALID_KEY_CACHE_MAX_ENTRIES) {
|
|
415
|
+
const oldest = validKeyCache.keys().next().value;
|
|
416
|
+
if (oldest !== undefined) validKeyCache.delete(oldest);
|
|
417
|
+
}
|
|
418
|
+
validKeyCache.set(cacheKey, Date.now() + VALID_KEY_CACHE_TTL_MS);
|
|
419
|
+
}
|
|
420
|
+
return result;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// Tests only: forget cached verdicts between cases.
|
|
424
|
+
export function clearValidKeyCache(): void {
|
|
425
|
+
validKeyCache.clear();
|
|
426
|
+
inFlightProbes.clear();
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Why the envelope check: api.conductor.is answers through Cloudflare in front of Render (verified live
|
|
430
|
+
// 2026-10-20: server: cloudflare, cf-ray, x-render-origin-server: Render), so a WAF block, managed challenge,
|
|
431
|
+
// rate-limit rule or Under Attack page (text/html 403) or a Cloudflare Access page (text/html 401) would
|
|
432
|
+
// otherwise read as a deleted key and turn every tools/call from every client (hosted Claude, Claude Code,
|
|
433
|
+
// Cursor, VS Code, Codex, mcp-remote, the npx bridge) into a sign-in 401, with hosted Claude re-consenting and
|
|
434
|
+
// minting a key row per retry. The API's own rejection is always application/json with the envelope
|
|
435
|
+
// { "error": { "code": ... } } (middleware/global-error-formatter.ts). 'unknown' is treated as valid by the
|
|
436
|
+
// caller (fail open). The body is always consumed or cancelled (an unread body pins the undici socket until
|
|
437
|
+
// GC) and never logged. The token is never logged. After EVERY probe, one structured line; the warn on
|
|
438
|
+
// 'unknown' is what makes a silently broken probe path (route renamed, DNS, permanent timeout, edge block)
|
|
439
|
+
// visible instead of reading as "every key is valid" forever.
|
|
440
|
+
async function probeKey(
|
|
441
|
+
token: string,
|
|
442
|
+
config: OAuthResourceConfig,
|
|
443
|
+
mcpSessionId: string | undefined,
|
|
444
|
+
): Promise<KeyProbeResult> {
|
|
445
|
+
const startedAt = Date.now();
|
|
446
|
+
let result: KeyProbeResult = { verdict: 'unknown' };
|
|
447
|
+
let status: number | null = null;
|
|
448
|
+
let contentType: string | null = null;
|
|
449
|
+
let cfRay: string | null = null;
|
|
450
|
+
let conductorRequestId: string | null = null;
|
|
451
|
+
let error: string | undefined;
|
|
452
|
+
try {
|
|
453
|
+
const response = await fetch(`${config.apiBaseUrl}${KEY_PROBE_PATH}`, {
|
|
454
|
+
method: 'GET',
|
|
455
|
+
headers: {
|
|
456
|
+
Authorization: `Bearer ${token}`,
|
|
457
|
+
Accept: 'application/json',
|
|
458
|
+
'User-Agent': KEY_PROBE_USER_AGENT,
|
|
459
|
+
},
|
|
460
|
+
signal: AbortSignal.timeout(KEY_PROBE_TIMEOUT_MS),
|
|
461
|
+
redirect: 'manual',
|
|
462
|
+
});
|
|
463
|
+
status = response.status;
|
|
464
|
+
contentType = mediaTypeOf(response.headers.get('content-type'));
|
|
465
|
+
cfRay = response.headers.get('cf-ray');
|
|
466
|
+
conductorRequestId = response.headers.get('conductor-request-id');
|
|
467
|
+
result = await classifyProbeResponse(response, contentType);
|
|
468
|
+
} catch (thrown) {
|
|
469
|
+
// timeout, DNS, reset, ECONNREFUSED
|
|
470
|
+
// undici's message is always "fetch failed"; the cause says refused, DNS, reset or bad port.
|
|
471
|
+
const cause = thrown instanceof Error ? (thrown as { cause?: unknown }).cause : undefined;
|
|
472
|
+
const causeText =
|
|
473
|
+
cause instanceof Error ?
|
|
474
|
+
`${(cause as { code?: string }).code ?? cause.name}: ${cause.message}`
|
|
475
|
+
: undefined;
|
|
476
|
+
error = [thrown instanceof Error ? thrown.message : String(thrown), causeText]
|
|
477
|
+
.filter(Boolean)
|
|
478
|
+
.join(' / ');
|
|
479
|
+
}
|
|
480
|
+
const { verdict, code } = result;
|
|
481
|
+
error ??= result.error;
|
|
482
|
+
const keyProbe = {
|
|
483
|
+
verdict,
|
|
484
|
+
...(code !== undefined && { code }),
|
|
485
|
+
status,
|
|
486
|
+
ms: Date.now() - startedAt,
|
|
487
|
+
contentType,
|
|
488
|
+
cfRay,
|
|
489
|
+
conductorRequestId,
|
|
490
|
+
...(error !== undefined && { error }),
|
|
491
|
+
};
|
|
492
|
+
getLogger()[verdict === 'unknown' ? 'warn' : 'info']({ mcpSessionId, keyProbe }, 'key probe');
|
|
493
|
+
return result;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// The probe reads a nonexistent end user, so the real API answers a live key 404 RESOURCE_MISSING and a dead or
|
|
497
|
+
// publishable key 401/403 with a code in KEY_PROBE_REJECTION_CODES, always application/json with Conductor's
|
|
498
|
+
// envelope. Anything else is 'unknown' (fail open, logged as a warning): a 2xx (the real API never sends one
|
|
499
|
+
// here, so CONDUCTOR_BASE_URL points somewhere else), another 404 (a moved route's UNRECOGNIZED_REQUEST_URL),
|
|
500
|
+
// an edge HTML page, another code, 3xx, 429 or 5xx. The body is read under the same 3 s abort signal.
|
|
501
|
+
async function classifyProbeResponse(
|
|
502
|
+
response: Response,
|
|
503
|
+
contentType: string | null,
|
|
504
|
+
): Promise<KeyProbeResult> {
|
|
505
|
+
const answersWithEnvelope = response.status === 404 || response.status === 401 || response.status === 403;
|
|
506
|
+
if (!answersWithEnvelope || contentType !== 'application/json') {
|
|
507
|
+
await discardBody(response);
|
|
508
|
+
return { verdict: 'unknown' };
|
|
509
|
+
}
|
|
510
|
+
let code: string | undefined;
|
|
511
|
+
try {
|
|
512
|
+
code = errorCodeOf(JSON.parse(await response.text()));
|
|
513
|
+
} catch (thrown) {
|
|
514
|
+
// The 3 s abort firing mid-body, or a body that is not JSON.
|
|
515
|
+
return { verdict: 'unknown', error: thrown instanceof Error ? thrown.message : String(thrown) };
|
|
516
|
+
}
|
|
517
|
+
if (response.status === 404) return { verdict: code === 'RESOURCE_MISSING' ? 'valid' : 'unknown' };
|
|
518
|
+
return code !== undefined && KEY_PROBE_REJECTION_CODES.has(code) ?
|
|
519
|
+
{ verdict: 'invalid', code }
|
|
520
|
+
: { verdict: 'unknown' };
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// error.code from Conductor's error envelope { "error": { "code": ... } }, if present.
|
|
524
|
+
function errorCodeOf(parsed: unknown): string | undefined {
|
|
525
|
+
if (typeof parsed !== 'object' || parsed === null) return undefined;
|
|
526
|
+
const error = (parsed as { error?: unknown }).error;
|
|
527
|
+
if (typeof error !== 'object' || error === null) return undefined;
|
|
528
|
+
const code = (error as { code?: unknown }).code;
|
|
529
|
+
return typeof code === 'string' ? code : undefined;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
async function discardBody(response: Response): Promise<void> {
|
|
533
|
+
await response.body?.cancel().catch(() => undefined);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// content-type before ";", trimmed, lowercased
|
|
537
|
+
function mediaTypeOf(contentType: string | null): string | null {
|
|
538
|
+
const mediaType = contentType?.split(';')[0]?.trim().toLowerCase();
|
|
539
|
+
return mediaType ? mediaType : null;
|
|
540
|
+
}
|
package/src/server.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { McpOptions } from './options';
|
|
|
18
18
|
import { blockedMethodsForCodeTool } from './methods';
|
|
19
19
|
import { HandlerFunction, McpRequestContext, ToolCallResult, McpTool } from './types';
|
|
20
20
|
|
|
21
|
-
export const VERSION = '
|
|
21
|
+
export const VERSION = '15.0.0'; // x-release-please-version
|
|
22
22
|
|
|
23
23
|
export const newMcpServer = async ({
|
|
24
24
|
stainlessApiKey,
|
|
@@ -30,7 +30,7 @@ export const newMcpServer = async ({
|
|
|
30
30
|
new McpServer(
|
|
31
31
|
{
|
|
32
32
|
name: 'conductor_node_api',
|
|
33
|
-
version: '
|
|
33
|
+
version: '15.0.0', // x-release-please-version
|
|
34
34
|
},
|
|
35
35
|
{
|
|
36
36
|
instructions: await getInstructions({ stainlessApiKey, customInstructionsPath }),
|
|
@@ -58,6 +58,7 @@ export async function initMcpServer(params: {
|
|
|
58
58
|
upstreamClientEnvs?: Record<string, string> | undefined;
|
|
59
59
|
mcpSessionId?: string | undefined;
|
|
60
60
|
mcpClientInfo?: { name: string; version: string } | undefined;
|
|
61
|
+
userAgent?: string | undefined; // conductor patch (telemetry.ts)
|
|
61
62
|
}) {
|
|
62
63
|
const server = params.server instanceof McpServer ? params.server.server : params.server;
|
|
63
64
|
|
|
@@ -121,7 +122,9 @@ export async function initMcpServer(params: {
|
|
|
121
122
|
};
|
|
122
123
|
});
|
|
123
124
|
|
|
124
|
-
|
|
125
|
+
// Conductor patch: `extra.signal` is the SDK's per-request abort signal, which fires when http.ts closes
|
|
126
|
+
// the transport on the client's socket close; the execute tool races its Deno worker against it.
|
|
127
|
+
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
125
128
|
const { name, arguments: args } = request.params;
|
|
126
129
|
const mcpTool = toolMap[name];
|
|
127
130
|
if (!mcpTool) {
|
|
@@ -151,6 +154,8 @@ export async function initMcpServer(params: {
|
|
|
151
154
|
upstreamClientEnvs: params.upstreamClientEnvs,
|
|
152
155
|
mcpSessionId: params.mcpSessionId,
|
|
153
156
|
mcpClientInfo: params.mcpClientInfo,
|
|
157
|
+
signal: extra.signal, // conductor patch
|
|
158
|
+
userAgent: params.userAgent, // conductor patch
|
|
154
159
|
},
|
|
155
160
|
args,
|
|
156
161
|
});
|