@ai-ecoverse/mcpcat 0.9.0 → 0.10.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.
@@ -25,8 +25,10 @@ __export(node_stub_exports, {
25
25
  access: () => access,
26
26
  basename: () => basename,
27
27
  constants: () => constants,
28
+ createHash: () => createHash,
28
29
  createInterface: () => createInterface,
29
30
  createRequire: () => createRequire,
31
+ createServer: () => createServer,
30
32
  default: () => node_stub_default,
31
33
  deprecate: () => deprecate,
32
34
  dirname: () => dirname,
@@ -42,6 +44,7 @@ __export(node_stub_exports, {
42
44
  pid: () => pid,
43
45
  platform: () => platform,
44
46
  promisify: () => promisify,
47
+ randomBytes: () => randomBytes,
45
48
  readFile: () => readFile,
46
49
  rename: () => rename,
47
50
  resolve: () => resolve,
@@ -115,6 +118,15 @@ function deprecate() {
115
118
  function createRequire() {
116
119
  return () => "";
117
120
  }
121
+ function createServer() {
122
+ throw new Error("not available in kernel");
123
+ }
124
+ function createHash() {
125
+ throw new Error("not available in kernel");
126
+ }
127
+ function randomBytes() {
128
+ throw new Error("not available in kernel");
129
+ }
118
130
  var node_stub_default, constants, Readable, Writable, Stream, env, pid, platform, EventEmitter, Worker, workerData, parentPort;
119
131
  var init_node_stub = __esm({
120
132
  "src/stubs/node-stub.ts"() {
@@ -5090,6 +5102,176 @@ function mergeArgs(base, flags) {
5090
5102
  return result;
5091
5103
  }
5092
5104
 
5105
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/callback.js
5106
+ init_node_stub();
5107
+ function plainText(page) {
5108
+ if (page.ok)
5109
+ return "Authorization complete. You may close this window.";
5110
+ return page.details ? `${page.message}
5111
+
5112
+ ${page.details}` : page.message;
5113
+ }
5114
+ var OAuthCallbackServer = class _OAuthCallbackServer {
5115
+ redirectUrl;
5116
+ server;
5117
+ paths;
5118
+ timeoutMs;
5119
+ renderPage;
5120
+ pending = /* @__PURE__ */ new Map();
5121
+ constructor(server, redirectUrl, paths, timeoutMs, renderPage) {
5122
+ this.server = server;
5123
+ this.redirectUrl = redirectUrl;
5124
+ this.paths = paths;
5125
+ this.timeoutMs = timeoutMs;
5126
+ this.renderPage = renderPage;
5127
+ }
5128
+ static async listen(options = {}) {
5129
+ const host = options.host ?? "127.0.0.1";
5130
+ const redirectHost = options.redirectHost ?? host;
5131
+ const path = options.path ?? "/callback";
5132
+ let instance;
5133
+ const server = createServer((request, response) => instance?.handle(request.url ?? "/", response));
5134
+ await new Promise((resolve2, reject) => {
5135
+ server.once("error", reject);
5136
+ server.listen(options.port ?? 0, host, () => {
5137
+ server.off("error", reject);
5138
+ resolve2();
5139
+ });
5140
+ });
5141
+ const address = server.address();
5142
+ if (!address || typeof address === "string")
5143
+ throw new Error("OAuth callback server did not bind to TCP");
5144
+ instance = new _OAuthCallbackServer(server, `http://${redirectHost.includes(":") ? `[${redirectHost}]` : redirectHost}:${address.port}${path}`, [path, ...options.extraPaths ?? []], options.timeoutMs ?? 5 * 6e4, options.renderPage);
5145
+ return instance;
5146
+ }
5147
+ /**
5148
+ * Wait for the authorization response with `state`. With `path`, a response on another path fails, so
5149
+ * a server-specific redirect URI can tell authorization servers apart (RFC 9700 section 4.4.2.2).
5150
+ */
5151
+ waitForCallback(state, path) {
5152
+ if (this.pending.has(state))
5153
+ throw new Error("OAuth state is already pending");
5154
+ return new Promise((resolve2, reject) => {
5155
+ const timer = setTimeout(() => {
5156
+ this.pending.delete(state);
5157
+ reject(new Error("OAuth callback timed out"));
5158
+ }, this.timeoutMs);
5159
+ this.pending.set(state, { resolve: resolve2, reject, timer, path });
5160
+ });
5161
+ }
5162
+ async close() {
5163
+ for (const pending of this.pending.values()) {
5164
+ clearTimeout(pending.timer);
5165
+ pending.reject(new Error("OAuth callback server closed"));
5166
+ }
5167
+ this.pending.clear();
5168
+ await new Promise((resolve2, reject) => {
5169
+ this.server.close((error) => error ? reject(error) : resolve2());
5170
+ });
5171
+ }
5172
+ reply(response, status, page) {
5173
+ if (this.renderPage) {
5174
+ response.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
5175
+ response.end(this.renderPage(page));
5176
+ } else {
5177
+ response.writeHead(status, { "content-type": "text/plain; charset=utf-8" }).end(plainText(page));
5178
+ }
5179
+ }
5180
+ handle(rawUrl, response) {
5181
+ const url = new URL(rawUrl, this.redirectUrl);
5182
+ if (!this.paths.includes(url.pathname)) {
5183
+ this.reply(response, 404, { ok: false, message: "Not found" });
5184
+ return;
5185
+ }
5186
+ const state = url.searchParams.get("state");
5187
+ const pending = state ? this.pending.get(state) : void 0;
5188
+ if (!state || !pending) {
5189
+ this.reply(response, 400, { ok: false, message: "Invalid or expired OAuth state" });
5190
+ return;
5191
+ }
5192
+ clearTimeout(pending.timer);
5193
+ this.pending.delete(state);
5194
+ if (pending.path !== void 0 && url.pathname !== pending.path) {
5195
+ pending.reject(new Error("The authorization response arrived on another redirect URI"));
5196
+ this.reply(response, 400, { ok: false, message: "Unexpected redirect URI" });
5197
+ return;
5198
+ }
5199
+ const error = url.searchParams.get("error");
5200
+ if (error) {
5201
+ const description = url.searchParams.get("error_description") ?? error;
5202
+ pending.reject(new Error(description));
5203
+ this.reply(response, 200, {
5204
+ ok: false,
5205
+ message: "Authorization failed. You may close this window.",
5206
+ details: description
5207
+ });
5208
+ return;
5209
+ }
5210
+ const code = url.searchParams.get("code");
5211
+ if (!code) {
5212
+ pending.reject(new Error("OAuth callback did not include an authorization code"));
5213
+ this.reply(response, 400, { ok: false, message: "Missing authorization code" });
5214
+ return;
5215
+ }
5216
+ const iss = url.searchParams.get("iss");
5217
+ pending.resolve({ code, state, ...iss ? { iss } : {} });
5218
+ this.reply(response, 200, { ok: true });
5219
+ }
5220
+ };
5221
+
5222
+ // node_modules/@earendil-works/pi-mcp/dist/protocol/types.js
5223
+ var LATEST_PROTOCOL_VERSION = "2025-11-25";
5224
+ var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05"];
5225
+
5226
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/errors.js
5227
+ var OAuthError = class extends Error {
5228
+ code;
5229
+ errorUri;
5230
+ constructor(code, message, errorUri) {
5231
+ super(message || code);
5232
+ this.name = "OAuthError";
5233
+ this.code = code;
5234
+ this.errorUri = errorUri;
5235
+ }
5236
+ };
5237
+ var OAuthIssuerMismatchError = class extends Error {
5238
+ /** `undefined` when no authorization server metadata was discovered. */
5239
+ expected;
5240
+ /** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */
5241
+ received;
5242
+ constructor(expected, received) {
5243
+ const format = (issuer) => issuer === void 0 ? "none" : JSON.stringify(issuer);
5244
+ super(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`);
5245
+ this.name = "OAuthIssuerMismatchError";
5246
+ this.expected = expected;
5247
+ this.received = received;
5248
+ }
5249
+ };
5250
+ var OAuthInsecureEndpointError = class extends Error {
5251
+ endpoint;
5252
+ constructor(endpoint) {
5253
+ super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`);
5254
+ this.name = "OAuthInsecureEndpointError";
5255
+ this.endpoint = endpoint;
5256
+ }
5257
+ };
5258
+ var OAuthRegistrationError = class extends Error {
5259
+ status;
5260
+ body;
5261
+ constructor(status, body) {
5262
+ super(`OAuth dynamic client registration failed with status ${status}: ${body}`);
5263
+ this.name = "OAuthRegistrationError";
5264
+ this.status = status;
5265
+ this.body = body;
5266
+ }
5267
+ };
5268
+ var McpOAuthAuthorizationRequiredError = class extends Error {
5269
+ constructor() {
5270
+ super("MCP OAuth authorization requires user interaction");
5271
+ this.name = "McpOAuthAuthorizationRequiredError";
5272
+ }
5273
+ };
5274
+
5093
5275
  // node_modules/@earendil-works/pi-mcp/dist/protocol/jsonrpc.js
5094
5276
  var JSON_RPC_ERROR_CODES = {
5095
5277
  parseError: -32700,
@@ -5158,9 +5340,726 @@ function parseJsonRpcMessage(value) {
5158
5340
  throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid JSON-RPC message");
5159
5341
  }
5160
5342
 
5161
- // node_modules/@earendil-works/pi-mcp/dist/protocol/types.js
5162
- var LATEST_PROTOCOL_VERSION = "2025-11-25";
5163
- var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05"];
5343
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/types.js
5344
+ function object(value, name) {
5345
+ if (!isObject(value))
5346
+ throw new Error(`Invalid ${name}`);
5347
+ return value;
5348
+ }
5349
+ function compact(value) {
5350
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
5351
+ }
5352
+ function requiredString(value, name) {
5353
+ if (typeof value !== "string" || value.length === 0)
5354
+ throw new Error(`Invalid ${name}`);
5355
+ return value;
5356
+ }
5357
+ function absent(value) {
5358
+ return value === void 0 || value === null || value === "";
5359
+ }
5360
+ function optionalString(value, name) {
5361
+ if (absent(value))
5362
+ return void 0;
5363
+ return requiredString(value, name);
5364
+ }
5365
+ function optionalStrings(value, name) {
5366
+ if (value === void 0 || value === null)
5367
+ return void 0;
5368
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string"))
5369
+ throw new Error(`Invalid ${name}`);
5370
+ return [...value];
5371
+ }
5372
+ function safeUrl(value, name) {
5373
+ const text = requiredString(value, name);
5374
+ if (!URL.canParse(text))
5375
+ throw new Error(`Invalid ${name}`);
5376
+ const url = new URL(text);
5377
+ if (["javascript:", "data:", "vbscript:"].includes(url.protocol))
5378
+ throw new Error(`Invalid ${name}`);
5379
+ return text;
5380
+ }
5381
+ function optionalUrl(value, name) {
5382
+ return absent(value) ? void 0 : safeUrl(value, name);
5383
+ }
5384
+ function parseProtectedResourceMetadata(value) {
5385
+ const input = object(value, "OAuth protected resource metadata");
5386
+ return compact({
5387
+ ...input,
5388
+ resource: safeUrl(input.resource, "OAuth protected resource metadata resource"),
5389
+ authorization_servers: optionalStrings(input.authorization_servers, "authorization_servers")?.map((url) => safeUrl(url, "authorization server URL")),
5390
+ scopes_supported: optionalStrings(input.scopes_supported, "scopes_supported")
5391
+ });
5392
+ }
5393
+ function parseAuthorizationServerMetadata(value) {
5394
+ const input = object(value, "authorization server metadata");
5395
+ const responseTypes = optionalStrings(input.response_types_supported, "response_types_supported");
5396
+ if (!responseTypes)
5397
+ throw new Error("Invalid response_types_supported");
5398
+ return compact({
5399
+ ...input,
5400
+ issuer: safeUrl(input.issuer, "authorization server issuer"),
5401
+ authorization_endpoint: safeUrl(input.authorization_endpoint, "authorization endpoint"),
5402
+ token_endpoint: safeUrl(input.token_endpoint, "token endpoint"),
5403
+ registration_endpoint: optionalUrl(input.registration_endpoint, "registration endpoint"),
5404
+ scopes_supported: optionalStrings(input.scopes_supported, "scopes_supported"),
5405
+ response_types_supported: responseTypes,
5406
+ grant_types_supported: optionalStrings(input.grant_types_supported, "grant_types_supported"),
5407
+ token_endpoint_auth_methods_supported: optionalStrings(input.token_endpoint_auth_methods_supported, "token_endpoint_auth_methods_supported"),
5408
+ code_challenge_methods_supported: optionalStrings(input.code_challenge_methods_supported, "code_challenge_methods_supported"),
5409
+ client_id_metadata_document_supported: typeof input.client_id_metadata_document_supported === "boolean" ? input.client_id_metadata_document_supported : void 0,
5410
+ authorization_response_iss_parameter_supported: typeof input.authorization_response_iss_parameter_supported === "boolean" ? input.authorization_response_iss_parameter_supported : void 0
5411
+ });
5412
+ }
5413
+ function parseOAuthTokens(value) {
5414
+ const input = object(value, "OAuth token response");
5415
+ const expires = absent(input.expires_in) ? void 0 : Number(input.expires_in);
5416
+ if (expires !== void 0 && !Number.isFinite(expires))
5417
+ throw new Error("Invalid expires_in");
5418
+ return compact({
5419
+ access_token: requiredString(input.access_token, "access_token"),
5420
+ token_type: requiredString(input.token_type, "token_type"),
5421
+ expires_in: expires,
5422
+ scope: optionalString(input.scope, "scope"),
5423
+ refresh_token: optionalString(input.refresh_token, "refresh_token"),
5424
+ id_token: optionalString(input.id_token, "id_token")
5425
+ });
5426
+ }
5427
+ function parseClientInformation(value) {
5428
+ const input = object(value, "OAuth client registration response");
5429
+ return compact({
5430
+ ...input,
5431
+ client_id: requiredString(input.client_id, "client_id"),
5432
+ client_secret: optionalString(input.client_secret, "client_secret"),
5433
+ client_id_issued_at: typeof input.client_id_issued_at === "number" ? input.client_id_issued_at : void 0,
5434
+ client_secret_expires_at: typeof input.client_secret_expires_at === "number" ? input.client_secret_expires_at : void 0,
5435
+ redirect_uris: optionalStrings(input.redirect_uris, "redirect_uris") ?? []
5436
+ });
5437
+ }
5438
+
5439
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/discovery.js
5440
+ function discard(response) {
5441
+ void response?.body?.cancel().catch(() => {
5442
+ });
5443
+ }
5444
+ function isDiscoveryMiss(status) {
5445
+ return status >= 400 && status < 500 || status === 502;
5446
+ }
5447
+ function pathSuffix(pathname) {
5448
+ return pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
5449
+ }
5450
+ function field(header, name) {
5451
+ const match = header.match(new RegExp(String.raw`(?:^|[,\s])${name}=(?:"([^"]*)"|([^\s,]+))`, "i"));
5452
+ return match?.[1] || match?.[2] || void 0;
5453
+ }
5454
+ function parseWwwAuthenticate(header) {
5455
+ if (!header)
5456
+ return {};
5457
+ const scheme = header.trimStart().split(/\s+/, 1)[0]?.toLowerCase();
5458
+ if (scheme !== "bearer" && scheme !== "dpop")
5459
+ return {};
5460
+ const resourceMetadata = field(header, "resource_metadata");
5461
+ let resourceMetadataUrl;
5462
+ if (resourceMetadata) {
5463
+ try {
5464
+ resourceMetadataUrl = new URL(resourceMetadata);
5465
+ } catch {
5466
+ }
5467
+ }
5468
+ return {
5469
+ resourceMetadataUrl,
5470
+ scope: field(header, "scope"),
5471
+ error: field(header, "error"),
5472
+ errorDescription: field(header, "error_description")
5473
+ };
5474
+ }
5475
+ async function fetchMetadata(url, fetch, protocolVersion, signal) {
5476
+ return fetch(url, {
5477
+ headers: { Accept: "application/json", "MCP-Protocol-Version": protocolVersion },
5478
+ signal
5479
+ });
5480
+ }
5481
+ async function discoverProtectedResourceMetadata(serverUrl, options = {}) {
5482
+ const server = new URL(serverUrl);
5483
+ const fetch = options.fetch ?? globalThis.fetch;
5484
+ const version = options.protocolVersion ?? LATEST_PROTOCOL_VERSION;
5485
+ let response = await fetchMetadata(options.resourceMetadataUrl ? new URL(options.resourceMetadataUrl) : new URL(`/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`, server.origin), fetch, version, options.signal);
5486
+ if (!options.resourceMetadataUrl && server.pathname !== "/" && isDiscoveryMiss(response.status)) {
5487
+ discard(response);
5488
+ response = await fetchMetadata(new URL("/.well-known/oauth-protected-resource", server.origin), fetch, version, options.signal);
5489
+ }
5490
+ if (!response.ok) {
5491
+ discard(response);
5492
+ throw new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);
5493
+ }
5494
+ return parseProtectedResourceMetadata(await response.json());
5495
+ }
5496
+ function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl) {
5497
+ const issuer = new URL(authorizationServerUrl);
5498
+ const path = pathSuffix(issuer.pathname);
5499
+ const urls = [
5500
+ { url: new URL(`/.well-known/oauth-authorization-server${path}`, issuer.origin), type: "oauth" },
5501
+ { url: new URL(`/.well-known/openid-configuration${path}`, issuer.origin), type: "oidc" }
5502
+ ];
5503
+ if (path)
5504
+ urls.push({ url: new URL(`${path}/.well-known/openid-configuration`, issuer.origin), type: "oidc" });
5505
+ return urls;
5506
+ }
5507
+ async function discoverAuthorizationServerMetadata(authorizationServerUrl, options = {}) {
5508
+ const fetch = options.fetch ?? globalThis.fetch;
5509
+ for (const { url } of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)) {
5510
+ const response = await fetchMetadata(url, fetch, options.protocolVersion ?? LATEST_PROTOCOL_VERSION, options.signal);
5511
+ if (!response.ok) {
5512
+ discard(response);
5513
+ if (isDiscoveryMiss(response.status))
5514
+ continue;
5515
+ throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);
5516
+ }
5517
+ const metadata = parseAuthorizationServerMetadata(await response.json());
5518
+ if (!options.skipIssuerValidation) {
5519
+ const expected = String(authorizationServerUrl);
5520
+ const trim = (value) => value.endsWith("/") ? value.slice(0, -1) : value;
5521
+ if (trim(metadata.issuer) !== trim(expected))
5522
+ throw new OAuthIssuerMismatchError(expected, metadata.issuer);
5523
+ }
5524
+ return metadata;
5525
+ }
5526
+ return void 0;
5527
+ }
5528
+ async function discoverOAuthServerInfo(serverUrl, options = {}) {
5529
+ let resourceMetadata;
5530
+ try {
5531
+ resourceMetadata = await discoverProtectedResourceMetadata(serverUrl, {
5532
+ resourceMetadataUrl: options.resourceMetadataUrl,
5533
+ fetch: options.fetch,
5534
+ signal: options.signal
5535
+ });
5536
+ } catch (error) {
5537
+ if (error instanceof TypeError)
5538
+ throw error;
5539
+ }
5540
+ if (options.authorizationServerMetadataUrl) {
5541
+ const url = options.authorizationServerMetadataUrl;
5542
+ const response = await fetchMetadata(url, options.fetch ?? globalThis.fetch, LATEST_PROTOCOL_VERSION, options.signal);
5543
+ if (!response.ok) {
5544
+ discard(response);
5545
+ throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);
5546
+ }
5547
+ const metadata = parseAuthorizationServerMetadata(await response.json());
5548
+ return { authorizationServerUrl: metadata.issuer, authorizationServerMetadata: metadata, resourceMetadata };
5549
+ }
5550
+ const authorizationServerUrl = resourceMetadata?.authorization_servers?.[0] ?? String(new URL("/", serverUrl));
5551
+ return {
5552
+ authorizationServerUrl,
5553
+ authorizationServerMetadata: await discoverAuthorizationServerMetadata(authorizationServerUrl, {
5554
+ fetch: options.fetch,
5555
+ skipIssuerValidation: options.skipIssuerValidation,
5556
+ signal: options.signal
5557
+ }),
5558
+ resourceMetadata
5559
+ };
5560
+ }
5561
+ function resourceUrlFromServerUrl(value) {
5562
+ const url = new URL(value);
5563
+ url.hash = "";
5564
+ return url;
5565
+ }
5566
+ function selectResource(serverUrl, metadata) {
5567
+ if (!metadata)
5568
+ return void 0;
5569
+ const requested = resourceUrlFromServerUrl(serverUrl);
5570
+ const configured = new URL(metadata.resource);
5571
+ if (requested.origin !== configured.origin) {
5572
+ throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);
5573
+ }
5574
+ const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : `${requested.pathname}/`;
5575
+ const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : `${configured.pathname}/`;
5576
+ if (!requestedPath.startsWith(configuredPath)) {
5577
+ throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);
5578
+ }
5579
+ return metadata.resource;
5580
+ }
5581
+
5582
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/flow.js
5583
+ function loopback(hostname) {
5584
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
5585
+ }
5586
+ function applicationType(redirectUris) {
5587
+ const native = redirectUris.some((uri) => {
5588
+ if (!URL.canParse(uri))
5589
+ return false;
5590
+ const url = new URL(uri);
5591
+ return url.protocol !== "http:" && url.protocol !== "https:" || loopback(url.hostname);
5592
+ });
5593
+ return native ? "native" : "web";
5594
+ }
5595
+ function secureEndpoint(value) {
5596
+ const url = new URL(value);
5597
+ if (url.protocol !== "https:" && !loopback(url.hostname))
5598
+ throw new OAuthInsecureEndpointError(url.href);
5599
+ return url;
5600
+ }
5601
+ function selectClientAuthMethod(information, supported) {
5602
+ const hinted = "token_endpoint_auth_method" in information ? information.token_endpoint_auth_method : void 0;
5603
+ if (hinted && ["client_secret_basic", "client_secret_post", "none"].includes(hinted) && (supported.length === 0 || supported.includes(hinted))) {
5604
+ return hinted;
5605
+ }
5606
+ if (supported.length === 0)
5607
+ return information.client_secret ? "client_secret_basic" : "none";
5608
+ if (information.client_secret && supported.includes("client_secret_basic"))
5609
+ return "client_secret_basic";
5610
+ if (information.client_secret && supported.includes("client_secret_post"))
5611
+ return "client_secret_post";
5612
+ if (supported.includes("none"))
5613
+ return "none";
5614
+ return information.client_secret ? "client_secret_post" : "none";
5615
+ }
5616
+ function applyClientAuthentication(method, information, headers, params) {
5617
+ if (method === "client_secret_basic") {
5618
+ if (!information.client_secret)
5619
+ throw new Error("client_secret_basic requires a client secret");
5620
+ headers.set("Authorization", `Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`);
5621
+ } else {
5622
+ params.set("client_id", information.client_id);
5623
+ if (method === "client_secret_post" && information.client_secret)
5624
+ params.set("client_secret", information.client_secret);
5625
+ }
5626
+ }
5627
+ async function pkce() {
5628
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
5629
+ const verifier = Buffer.from(bytes).toString("base64url");
5630
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
5631
+ return { verifier, challenge: Buffer.from(digest).toString("base64url") };
5632
+ }
5633
+ async function startAuthorization(authorizationServerUrl, options) {
5634
+ const metadata = options.metadata;
5635
+ if (metadata && !metadata.response_types_supported.includes("code")) {
5636
+ throw new Error("Authorization server does not support authorization codes");
5637
+ }
5638
+ if (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes("S256")) {
5639
+ throw new Error("Authorization server does not support PKCE S256");
5640
+ }
5641
+ const url = new URL(metadata?.authorization_endpoint ?? new URL("/authorize", authorizationServerUrl));
5642
+ const { verifier, challenge } = await pkce();
5643
+ url.searchParams.set("response_type", "code");
5644
+ url.searchParams.set("client_id", options.clientInformation.client_id);
5645
+ url.searchParams.set("code_challenge", challenge);
5646
+ url.searchParams.set("code_challenge_method", "S256");
5647
+ url.searchParams.set("redirect_uri", String(options.redirectUrl));
5648
+ if (options.state)
5649
+ url.searchParams.set("state", options.state);
5650
+ if (options.scope)
5651
+ url.searchParams.set("scope", options.scope);
5652
+ if (options.scope?.split(/\s+/).includes("offline_access"))
5653
+ url.searchParams.set("prompt", "consent");
5654
+ if (options.resource)
5655
+ url.searchParams.set("resource", options.resource);
5656
+ return { authorizationUrl: url, codeVerifier: verifier };
5657
+ }
5658
+ async function tokenRequest(authorizationServerUrl, options, params) {
5659
+ const url = secureEndpoint(options.metadata?.token_endpoint ?? new URL("/token", authorizationServerUrl));
5660
+ const headers = new Headers({ Accept: "application/json", "content-type": "application/x-www-form-urlencoded" });
5661
+ if (options.resource)
5662
+ params.set("resource", options.resource);
5663
+ if (options.addClientAuthentication) {
5664
+ await options.addClientAuthentication(headers, params, url, options.metadata);
5665
+ } else {
5666
+ applyClientAuthentication(selectClientAuthMethod(options.clientInformation, options.metadata?.token_endpoint_auth_methods_supported ?? []), options.clientInformation, headers, params);
5667
+ }
5668
+ const response = await (options.fetch ?? globalThis.fetch)(url, {
5669
+ method: "POST",
5670
+ headers,
5671
+ body: params,
5672
+ signal: options.signal
5673
+ });
5674
+ const text = await response.text();
5675
+ let value;
5676
+ try {
5677
+ value = JSON.parse(text);
5678
+ } catch {
5679
+ }
5680
+ if (isObject(value) && typeof value.error === "string") {
5681
+ throw new OAuthError(value.error, typeof value.error_description === "string" ? value.error_description : value.error, typeof value.error_uri === "string" ? value.error_uri : void 0);
5682
+ }
5683
+ if (!response.ok)
5684
+ throw new OAuthError("server_error", `HTTP ${response.status}: ${text}`);
5685
+ return parseOAuthTokens(value);
5686
+ }
5687
+ async function registerClient(authorizationServerUrl, options) {
5688
+ const endpoint = options.metadata?.registration_endpoint;
5689
+ if (options.metadata && !endpoint)
5690
+ throw new Error("Authorization server does not support dynamic client registration");
5691
+ const response = await (options.fetch ?? globalThis.fetch)(new URL(endpoint ?? new URL("/register", authorizationServerUrl)), {
5692
+ method: "POST",
5693
+ headers: { Accept: "application/json", "content-type": "application/json" },
5694
+ body: JSON.stringify({
5695
+ ...options.clientMetadata,
5696
+ application_type: options.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),
5697
+ ...options.scope ? { scope: options.scope } : {}
5698
+ }),
5699
+ signal: options.signal
5700
+ });
5701
+ if (!response.ok)
5702
+ throw new OAuthRegistrationError(response.status, await response.text());
5703
+ return parseClientInformation(await response.json());
5704
+ }
5705
+ async function exchangeAuthorizationCode(authorizationServerUrl, options) {
5706
+ return tokenRequest(authorizationServerUrl, options, new URLSearchParams({
5707
+ grant_type: "authorization_code",
5708
+ code: options.code,
5709
+ code_verifier: options.codeVerifier,
5710
+ redirect_uri: String(options.redirectUrl)
5711
+ }));
5712
+ }
5713
+ async function refreshAuthorization(authorizationServerUrl, options) {
5714
+ const tokens = await tokenRequest(authorizationServerUrl, options, new URLSearchParams({ grant_type: "refresh_token", refresh_token: options.refreshToken }));
5715
+ return { refresh_token: options.refreshToken, ...tokens };
5716
+ }
5717
+ function withScope(tokens, scope) {
5718
+ return tokens.scope === void 0 && scope ? { ...tokens, scope } : tokens;
5719
+ }
5720
+ function stepUpScope(granted, challenged) {
5721
+ if (!challenged)
5722
+ return void 0;
5723
+ const scopes = [granted, challenged].flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []);
5724
+ return [...new Set(scopes)].join(" ");
5725
+ }
5726
+ async function runFlow(provider, options) {
5727
+ const metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);
5728
+ const cached = metadataUrl ? void 0 : await provider.discoveryState?.();
5729
+ const discovered = cached?.authorizationServerUrl ? {
5730
+ authorizationServerUrl: cached.authorizationServerUrl,
5731
+ authorizationServerMetadata: cached.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {
5732
+ fetch: options.fetch,
5733
+ skipIssuerValidation: options.skipIssuerValidation,
5734
+ signal: options.signal
5735
+ }),
5736
+ resourceMetadata: cached.resourceMetadata
5737
+ } : await discoverOAuthServerInfo(options.serverUrl, {
5738
+ resourceMetadataUrl: options.resourceMetadataUrl,
5739
+ authorizationServerMetadataUrl: metadataUrl,
5740
+ fetch: options.fetch,
5741
+ skipIssuerValidation: options.skipIssuerValidation,
5742
+ signal: options.signal
5743
+ });
5744
+ if (!metadataUrl) {
5745
+ await provider.saveDiscoveryState?.({
5746
+ ...discovered,
5747
+ ...options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}
5748
+ });
5749
+ }
5750
+ const metadata = discovered.authorizationServerMetadata;
5751
+ const resource = selectResource(options.serverUrl, discovered.resourceMetadata);
5752
+ const scope = options.scope || discovered.resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
5753
+ const stored = await provider.clientInformation();
5754
+ const clientDocument = stored ? void 0 : provider.clientMetadataDocument?.(metadata);
5755
+ if (clientDocument) {
5756
+ const url = new URL(clientDocument.url);
5757
+ if (url.protocol !== "https:" || url.pathname === "/")
5758
+ throw new Error("Invalid OAuth client metadata URL");
5759
+ }
5760
+ let client = stored ?? (clientDocument && { client_id: clientDocument.url });
5761
+ if (!client) {
5762
+ if (options.authorizationCode)
5763
+ throw new Error("OAuth client information is missing during code exchange");
5764
+ if (!provider.saveClientInformation)
5765
+ throw new Error("OAuth client information cannot be persisted");
5766
+ client = await registerClient(discovered.authorizationServerUrl, {
5767
+ metadata,
5768
+ clientMetadata: provider.clientMetadata,
5769
+ scope,
5770
+ fetch: options.fetch,
5771
+ signal: options.signal
5772
+ });
5773
+ await provider.saveClientInformation(client);
5774
+ }
5775
+ const redirectUrl = clientDocument?.redirectUrl ?? provider.redirectUrl;
5776
+ const tokenOptions = {
5777
+ metadata,
5778
+ clientInformation: client,
5779
+ resource,
5780
+ addClientAuthentication: provider.addClientAuthentication,
5781
+ fetch: options.fetch,
5782
+ signal: options.signal
5783
+ };
5784
+ if (options.authorizationCode) {
5785
+ const iss = options.iss;
5786
+ if (iss !== void 0 || metadata?.authorization_response_iss_parameter_supported) {
5787
+ if (iss !== metadata?.issuer)
5788
+ throw new OAuthIssuerMismatchError(metadata?.issuer, iss);
5789
+ }
5790
+ const tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {
5791
+ ...tokenOptions,
5792
+ code: options.authorizationCode,
5793
+ codeVerifier: await provider.codeVerifier(),
5794
+ redirectUrl
5795
+ });
5796
+ await provider.saveTokens(withScope(tokens, scope));
5797
+ return "AUTHORIZED";
5798
+ }
5799
+ const existing = options.skipRefresh ? void 0 : await provider.tokens();
5800
+ if (existing?.refresh_token) {
5801
+ try {
5802
+ const tokens = await refreshAuthorization(discovered.authorizationServerUrl, {
5803
+ ...tokenOptions,
5804
+ refreshToken: existing.refresh_token
5805
+ });
5806
+ await provider.saveTokens(withScope(tokens, existing.scope));
5807
+ return "AUTHORIZED";
5808
+ } catch (error) {
5809
+ if (options.signal?.aborted || error instanceof OAuthInsecureEndpointError)
5810
+ throw error;
5811
+ if (error instanceof OAuthError && error.code !== "server_error")
5812
+ throw error;
5813
+ }
5814
+ }
5815
+ const state = await provider.state?.();
5816
+ const authorization = await startAuthorization(discovered.authorizationServerUrl, {
5817
+ metadata,
5818
+ clientInformation: client,
5819
+ redirectUrl,
5820
+ scope,
5821
+ state,
5822
+ resource
5823
+ });
5824
+ await provider.saveCodeVerifier(authorization.codeVerifier);
5825
+ await provider.redirectToAuthorization(authorization.authorizationUrl);
5826
+ return "REDIRECT";
5827
+ }
5828
+ async function authorizeMcp(provider, options) {
5829
+ try {
5830
+ return await runFlow(provider, options);
5831
+ } catch (error) {
5832
+ if (error instanceof OAuthError && ["invalid_client", "unauthorized_client"].includes(error.code)) {
5833
+ await provider.invalidateCredentials?.("all");
5834
+ return runFlow(provider, options);
5835
+ }
5836
+ if (error instanceof OAuthError && error.code === "invalid_grant") {
5837
+ await provider.invalidateCredentials?.("tokens");
5838
+ return runFlow(provider, options);
5839
+ }
5840
+ throw error;
5841
+ }
5842
+ }
5843
+
5844
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/provider.js
5845
+ var MemoryOAuthStateStore = class {
5846
+ value;
5847
+ load() {
5848
+ return this.value === void 0 ? void 0 : structuredClone(this.value);
5849
+ }
5850
+ save(state) {
5851
+ this.value = structuredClone(state);
5852
+ }
5853
+ };
5854
+ var McpOAuthProvider = class {
5855
+ redirectUrl;
5856
+ clientMetadata;
5857
+ clientMetadataDocument;
5858
+ serverUrl;
5859
+ configuredClient;
5860
+ store;
5861
+ onRedirect;
5862
+ writes = Promise.resolve();
5863
+ constructor(options) {
5864
+ this.serverUrl = String(new URL(options.serverUrl));
5865
+ this.redirectUrl = String(options.redirectUrl);
5866
+ this.clientMetadata = {
5867
+ ...options.clientMetadata,
5868
+ redirect_uris: options.clientMetadata.redirect_uris ?? [this.redirectUrl],
5869
+ grant_types: options.clientMetadata.grant_types ?? ["authorization_code", "refresh_token"],
5870
+ response_types: options.clientMetadata.response_types ?? ["code"],
5871
+ token_endpoint_auth_method: options.clientMetadata.token_endpoint_auth_method ?? (options.clientSecret ? "client_secret_post" : "none")
5872
+ };
5873
+ this.clientMetadataDocument = options.clientMetadataDocument;
5874
+ this.configuredClient = options.clientId ? { client_id: options.clientId, ...options.clientSecret ? { client_secret: options.clientSecret } : {} } : void 0;
5875
+ this.store = options.store ?? new MemoryOAuthStateStore();
5876
+ this.onRedirect = options.onRedirect;
5877
+ }
5878
+ async state() {
5879
+ const existing = (await this.load()).oauthState;
5880
+ if (existing)
5881
+ return existing;
5882
+ const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");
5883
+ await this.update((value) => ({ ...value, oauthState: state }));
5884
+ return state;
5885
+ }
5886
+ async clientInformation() {
5887
+ return this.configuredClient ?? (await this.load()).clientInformation;
5888
+ }
5889
+ async saveClientInformation(information) {
5890
+ if (this.configuredClient)
5891
+ return;
5892
+ await this.update((value) => ({ ...value, clientInformation: information }));
5893
+ }
5894
+ async tokens() {
5895
+ return (await this.load()).tokens;
5896
+ }
5897
+ async saveTokens(tokens) {
5898
+ const expiresAt = tokens.expires_in === void 0 ? void 0 : Date.now() + tokens.expires_in * 1e3;
5899
+ await this.update((value) => {
5900
+ const next = { ...value, tokens };
5901
+ if (expiresAt === void 0)
5902
+ delete next.tokensExpireAt;
5903
+ else
5904
+ next.tokensExpireAt = expiresAt;
5905
+ return next;
5906
+ });
5907
+ }
5908
+ async redirectToAuthorization(url) {
5909
+ await this.onRedirect(url);
5910
+ }
5911
+ async saveCodeVerifier(verifier) {
5912
+ await this.update((value) => ({ ...value, codeVerifier: verifier }));
5913
+ }
5914
+ async codeVerifier() {
5915
+ const verifier = (await this.load()).codeVerifier;
5916
+ if (!verifier)
5917
+ throw new Error("No OAuth PKCE code verifier is stored");
5918
+ return verifier;
5919
+ }
5920
+ async invalidateCredentials(kind) {
5921
+ await this.update((value) => {
5922
+ const next = { ...value };
5923
+ if (kind === "all" || kind === "client")
5924
+ delete next.clientInformation;
5925
+ if (kind === "all" || kind === "tokens") {
5926
+ delete next.tokens;
5927
+ delete next.tokensExpireAt;
5928
+ }
5929
+ if (kind === "all" || kind === "verifier")
5930
+ delete next.codeVerifier;
5931
+ if (kind === "all" || kind === "discovery")
5932
+ delete next.discovery;
5933
+ if (kind === "all")
5934
+ delete next.oauthState;
5935
+ return next;
5936
+ });
5937
+ }
5938
+ async saveDiscoveryState(discovery) {
5939
+ await this.update((value) => ({ ...value, discovery }));
5940
+ }
5941
+ async discoveryState() {
5942
+ return (await this.load()).discovery;
5943
+ }
5944
+ async load() {
5945
+ await this.writes;
5946
+ return this.own(await this.store.load());
5947
+ }
5948
+ async update(update) {
5949
+ this.writes = this.writes.then(async () => {
5950
+ await this.store.save(update(this.own(await this.store.load())));
5951
+ });
5952
+ await this.writes;
5953
+ }
5954
+ /** Stored state for another server URL is ignored so credentials never leak across servers. */
5955
+ own(state) {
5956
+ return state?.serverUrl === this.serverUrl ? state : { serverUrl: this.serverUrl };
5957
+ }
5958
+ };
5959
+
5960
+ // src/auth/auth-provider.ts
5961
+ var CIMD_URL = "https://mcpcat.sliccy.ai/oauth/client.json";
5962
+ var CLIENT_NAME = "mcpcat";
5963
+ var CALLBACK_HOST = "127.0.0.1";
5964
+ var CALLBACK_PATH = "/callback";
5965
+ var REQUEST_TIMEOUT_MS = 15e3;
5966
+ var REFRESH_SKEW_MS = 3e4;
5967
+ var FALLBACK_REDIRECT_URL = `http://${CALLBACK_HOST}${CALLBACK_PATH}`;
5968
+ function timedFetch(fetchImpl) {
5969
+ return (input, init) => {
5970
+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
5971
+ return fetchImpl(input, {
5972
+ ...init,
5973
+ signal: init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout
5974
+ });
5975
+ };
5976
+ }
5977
+ var SourceBackedStore = class {
5978
+ source;
5979
+ name;
5980
+ serverUrl;
5981
+ constructor(source, name, serverUrl) {
5982
+ this.source = source;
5983
+ this.name = name;
5984
+ this.serverUrl = serverUrl;
5985
+ }
5986
+ async load() {
5987
+ return this.source.load(this.name, this.serverUrl);
5988
+ }
5989
+ async save(state) {
5990
+ await this.source.save(this.name, this.serverUrl, state);
5991
+ }
5992
+ };
5993
+ function cimdFn(redirectUrl) {
5994
+ return (metadata) => {
5995
+ if (!metadata?.client_id_metadata_document_supported) return void 0;
5996
+ if (!metadata.token_endpoint_auth_methods_supported?.includes("none")) return void 0;
5997
+ if (!metadata.authorization_response_iss_parameter_supported) return void 0;
5998
+ return { url: CIMD_URL, redirectUrl };
5999
+ };
6000
+ }
6001
+ var AuthStepUpError = class extends Error {
6002
+ scope;
6003
+ target;
6004
+ constructor(scope, target) {
6005
+ super(scope ? `insufficient_scope: ${scope}` : "insufficient_scope");
6006
+ this.name = "AuthStepUpError";
6007
+ this.scope = scope;
6008
+ this.target = target;
6009
+ }
6010
+ };
6011
+ function createMcpAuthProvider(options) {
6012
+ const { name, serverUrl, source, oauth, platform: platform2 } = options;
6013
+ const store = new SourceBackedStore(source, name, serverUrl);
6014
+ let refreshing;
6015
+ const refresh = async (staleToken) => {
6016
+ refreshing ??= (async () => {
6017
+ const state = await store.load();
6018
+ if (state?.tokens?.access_token !== staleToken) return;
6019
+ if (!state?.tokens?.refresh_token) throw new McpOAuthAuthorizationRequiredError();
6020
+ const registered = state.clientInformation && "redirect_uris" in state.clientInformation ? state.clientInformation.redirect_uris : [];
6021
+ const redirectUrl = registered[0] ?? FALLBACK_REDIRECT_URL;
6022
+ const provider = new McpOAuthProvider({
6023
+ serverUrl,
6024
+ redirectUrl,
6025
+ clientMetadata: { client_name: oauth?.clientName ?? CLIENT_NAME },
6026
+ clientMetadataDocument: oauth?.clientId ? void 0 : cimdFn(redirectUrl),
6027
+ clientId: oauth?.clientId,
6028
+ clientSecret: oauth?.clientSecret,
6029
+ store,
6030
+ onRedirect() {
6031
+ }
6032
+ });
6033
+ const result = await authorizeMcp(provider, {
6034
+ serverUrl,
6035
+ authorizationServerMetadataUrl: oauth?.authServerMetadataUrl ? new URL(oauth.authServerMetadataUrl) : void 0,
6036
+ fetch: timedFetch(platform2.fetch)
6037
+ });
6038
+ if (result === "REDIRECT") throw new McpOAuthAuthorizationRequiredError();
6039
+ })().finally(() => {
6040
+ refreshing = void 0;
6041
+ });
6042
+ return refreshing;
6043
+ };
6044
+ return {
6045
+ async token() {
6046
+ await refreshing?.catch(() => void 0);
6047
+ const state = await store.load();
6048
+ const token = state?.tokens?.access_token;
6049
+ const expired = state?.tokensExpireAt !== void 0 && state.tokensExpireAt - REFRESH_SKEW_MS <= Date.now();
6050
+ if (!expired || !state?.tokens?.refresh_token) return token;
6051
+ await refresh(token).catch(() => void 0);
6052
+ return (await store.load())?.tokens?.access_token;
6053
+ },
6054
+ async onUnauthorized(context) {
6055
+ const challenge = parseWwwAuthenticate(context.response.headers.get("www-authenticate"));
6056
+ if (challenge.error === "insufficient_scope") {
6057
+ throw new AuthStepUpError(challenge.scope, options.name);
6058
+ }
6059
+ await refresh(context.token);
6060
+ }
6061
+ };
6062
+ }
5164
6063
 
5165
6064
  // node_modules/@earendil-works/pi-mcp/dist/client.js
5166
6065
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
@@ -5858,21 +6757,21 @@ async function consumeSseStream(stream, options) {
5858
6757
  if (line.startsWith(":"))
5859
6758
  return;
5860
6759
  const colon = line.indexOf(":");
5861
- const field = colon < 0 ? line : line.slice(0, colon);
6760
+ const field2 = colon < 0 ? line : line.slice(0, colon);
5862
6761
  let value = colon < 0 ? "" : line.slice(colon + 1);
5863
6762
  if (value.startsWith(" "))
5864
6763
  value = value.slice(1);
5865
- if (field === "data") {
6764
+ if (field2 === "data") {
5866
6765
  dataBytes += __mcpcat_byteLength(value) + (dataLines.length > 0 ? 1 : 0);
5867
6766
  if (dataBytes > maxEventBytes)
5868
6767
  throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
5869
6768
  dataLines.push(value);
5870
- } else if (field === "event")
6769
+ } else if (field2 === "event")
5871
6770
  eventName = value;
5872
- else if (field === "id" && !value.includes("\0")) {
6771
+ else if (field2 === "id" && !value.includes("\0")) {
5873
6772
  eventId = value;
5874
6773
  options.onId?.(value);
5875
- } else if (field === "retry" && /^\d+$/.test(value))
6774
+ } else if (field2 === "retry" && /^\d+$/.test(value))
5876
6775
  options.onRetry?.(Number(value));
5877
6776
  };
5878
6777
  try {
@@ -5935,7 +6834,7 @@ function needsAuthorization(response) {
5935
6834
  function isTransientStatus(status) {
5936
6835
  return status === 408 || status === 429 || status >= 500;
5937
6836
  }
5938
- function discard(response) {
6837
+ function discard2(response) {
5939
6838
  return response.body?.cancel().catch(() => {
5940
6839
  }) ?? Promise.resolve();
5941
6840
  }
@@ -5986,7 +6885,7 @@ var StreamableHttpTransport = class extends TransportEvents {
5986
6885
  await this.checkResponse(response);
5987
6886
  this.captureSession(response);
5988
6887
  if (!isJsonRpcRequest(message)) {
5989
- await discard(response);
6888
+ await discard2(response);
5990
6889
  if ("method" in message && message.method === "notifications/initialized")
5991
6890
  this.startGetStream();
5992
6891
  return;
@@ -6005,7 +6904,7 @@ var StreamableHttpTransport = class extends TransportEvents {
6005
6904
  void this.consumeResponseStream(response.body, message.id);
6006
6905
  return;
6007
6906
  }
6008
- await discard(response);
6907
+ await discard2(response);
6009
6908
  throw new McpHttpError(response.status, `Unsupported MCP response content type: ${type ?? "missing"}`);
6010
6909
  }
6011
6910
  async close() {
@@ -6020,7 +6919,7 @@ var StreamableHttpTransport = class extends TransportEvents {
6020
6919
  headers: this.buildHeaders({}, this.lastToken),
6021
6920
  signal: AbortSignal.timeout(1e3)
6022
6921
  });
6023
- await discard(response);
6922
+ await discard2(response);
6024
6923
  } catch {
6025
6924
  }
6026
6925
  }
@@ -6051,7 +6950,7 @@ var StreamableHttpTransport = class extends TransportEvents {
6051
6950
  try {
6052
6951
  await onUnauthorized({ response, serverUrl: this.url, fetch: this.fetch, token });
6053
6952
  } finally {
6054
- await discard(response);
6953
+ await discard2(response);
6055
6954
  }
6056
6955
  }
6057
6956
  }
@@ -6208,14 +7107,14 @@ var StreamableHttpTransport = class extends TransportEvents {
6208
7107
  }
6209
7108
  });
6210
7109
  if (response.status === 405) {
6211
- await discard(response);
7110
+ await discard2(response);
6212
7111
  return void 0;
6213
7112
  }
6214
7113
  await this.checkResponse(response);
6215
7114
  this.captureSession(response);
6216
7115
  const type = contentType(response);
6217
7116
  if (type !== "text/event-stream" || !response.body) {
6218
- await discard(response);
7117
+ await discard2(response);
6219
7118
  throw new McpHttpError(response.status, `Unsupported MCP GET response content type: ${type ?? "missing"}`);
6220
7119
  }
6221
7120
  return response.body;
@@ -6686,7 +7585,8 @@ function buildTransport(options) {
6686
7585
  return new StreamableHttpTransport({
6687
7586
  url: options.url,
6688
7587
  headers: options.headers,
6689
- fetch: options.fetchImpl
7588
+ fetch: options.fetchImpl,
7589
+ authProvider: options.authProvider
6690
7590
  });
6691
7591
  }
6692
7592
  if (!options.command) throw new Error("PiConnection requires either a url or a command");
@@ -6798,6 +7698,18 @@ async function connect(platform2, options) {
6798
7698
  });
6799
7699
  }
6800
7700
  if (!options.url) throw new Error("connect requires either a url or a command");
7701
+ if (options.authProvider) {
7702
+ const token = await options.authProvider.token();
7703
+ if (token) {
7704
+ return createPiConnection({
7705
+ url: options.url,
7706
+ headers: options.headers,
7707
+ fetchImpl: platform2.fetch,
7708
+ authProvider: options.authProvider,
7709
+ ...shared
7710
+ });
7711
+ }
7712
+ }
6801
7713
  if (options.protocolVersion && !options.protocolVersion.startsWith("2026")) {
6802
7714
  return createPiConnection({
6803
7715
  url: options.url,
@@ -6824,6 +7736,7 @@ async function connect(platform2, options) {
6824
7736
  url: options.url,
6825
7737
  headers: options.headers,
6826
7738
  fetchImpl: platform2.fetch,
7739
+ authProvider: options.authProvider,
6827
7740
  ...shared
6828
7741
  });
6829
7742
  }
@@ -7298,8 +8211,8 @@ async function formatOutput(platform2, result, json) {
7298
8211
  return result.ok ? 0 : isTimeout ? 124 : 1;
7299
8212
  }
7300
8213
  async function createSandbox(platform2, tools, globals, timeoutMs) {
7301
- const isKernel = platform2.packageDir !== void 0;
7302
- if (isKernel) {
8214
+ const isKernel2 = platform2.packageDir !== void 0;
8215
+ if (isKernel2) {
7303
8216
  const { InlineCodemodeSandbox: InlineCodemodeSandbox2 } = await Promise.resolve().then(() => (init_portable(), portable_exports));
7304
8217
  const wasm = await loadWasmKernel(platform2);
7305
8218
  return new InlineCodemodeSandbox2({ tools, globals, timeoutMs, wasm });
@@ -7424,8 +8337,8 @@ function resolveAliases(value) {
7424
8337
  }
7425
8338
  return out;
7426
8339
  }
7427
- function fail(server, message, field) {
7428
- return { server, ...field ? { field } : {}, message };
8340
+ function fail(server, message, field2) {
8341
+ return { server, ...field2 ? { field: field2 } : {}, message };
7429
8342
  }
7430
8343
  function validateCommon(name, value) {
7431
8344
  const exposures = EXPOSURES.map((e) => `"${e}"`).join(", ");
@@ -8846,7 +9759,7 @@ function argvForCommand(command, args) {
8846
9759
  if (args.error) return { error: args.error };
8847
9760
  const argv = [...command.path];
8848
9761
  for (const positional of command.positionals) {
8849
- const found = args.fields.find((field) => field.name === positional.name);
9762
+ const found = args.fields.find((field2) => field2.name === positional.name);
8850
9763
  if (!found) {
8851
9764
  if (positional.required) return { error: `missing ${positional.name}` };
8852
9765
  continue;
@@ -8865,7 +9778,7 @@ function argvForCommand(command, args) {
8865
9778
  function appendFlags(flags, fields) {
8866
9779
  const argv = [];
8867
9780
  for (const flag of flags) {
8868
- const found = fields.find((field) => field.name === flag.name);
9781
+ const found = fields.find((field2) => field2.name === flag.name);
8869
9782
  if (!found || found.value === false) continue;
8870
9783
  const encoded = encodeFlag(flag, found.value);
8871
9784
  if ("error" in encoded) return encoded;
@@ -10574,6 +11487,478 @@ async function handleMcpRequest(request, tools, call, serverName, version, allow
10574
11487
  };
10575
11488
  }
10576
11489
 
11490
+ // src/auth/oauth.ts
11491
+ var CALLBACK_HOST2 = "127.0.0.1";
11492
+ var CALLBACK_PATH2 = "/callback";
11493
+ var CIMD_URL2 = "https://mcpcat.sliccy.ai/oauth/client.json";
11494
+ var CLIENT_NAME2 = "mcpcat";
11495
+ var REQUEST_TIMEOUT_MS2 = 15e3;
11496
+ function timedFetch2(fetchImpl) {
11497
+ return (input, init) => {
11498
+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS2);
11499
+ return fetchImpl(input, {
11500
+ ...init,
11501
+ signal: init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout
11502
+ });
11503
+ };
11504
+ }
11505
+ function callbackSettings(oauth) {
11506
+ const raw = oauth?.callbackUrl ?? `http://${CALLBACK_HOST2}${CALLBACK_PATH2}`;
11507
+ const url = new URL(raw);
11508
+ const address = url.hostname.replace(/^\[|\]$/g, "");
11509
+ const port = url.port ? Number(url.port) : oauth?.callbackPort;
11510
+ let fixedRedirectUrl;
11511
+ if (url.port) fixedRedirectUrl = oauth?.callbackUrl;
11512
+ else if (port !== void 0) {
11513
+ url.port = String(port);
11514
+ fixedRedirectUrl = url.href;
11515
+ }
11516
+ return {
11517
+ host: address === "localhost" ? CALLBACK_HOST2 : address,
11518
+ redirectHost: address,
11519
+ port,
11520
+ path: url.pathname,
11521
+ fixedRedirectUrl
11522
+ };
11523
+ }
11524
+ function cimdForServer(metadata, redirectUrl) {
11525
+ if (!metadata?.client_id_metadata_document_supported) return void 0;
11526
+ if (!metadata.token_endpoint_auth_methods_supported?.includes("none")) return void 0;
11527
+ if (!metadata.authorization_response_iss_parameter_supported) return void 0;
11528
+ return {
11529
+ url: CIMD_URL2,
11530
+ redirectUrl
11531
+ };
11532
+ }
11533
+ function buildClientMetadataDocumentFn(oauth, redirectUrl) {
11534
+ if (oauth?.clientRegistration === "dcr") return void 0;
11535
+ if (oauth?.clientId) return void 0;
11536
+ return (metadata) => {
11537
+ if (oauth?.clientRegistration === "cimd") {
11538
+ if (!metadata?.client_id_metadata_document_supported || !metadata.token_endpoint_auth_methods_supported?.includes("none")) {
11539
+ return void 0;
11540
+ }
11541
+ if (!metadata.authorization_response_iss_parameter_supported) return void 0;
11542
+ return { url: CIMD_URL2, redirectUrl };
11543
+ }
11544
+ return cimdForServer(metadata, redirectUrl);
11545
+ };
11546
+ }
11547
+ function createProvider(serverUrl, store, oauth, redirectUrl, onRedirect) {
11548
+ const cimdFn2 = buildClientMetadataDocumentFn(oauth, redirectUrl);
11549
+ return new McpOAuthProvider({
11550
+ serverUrl,
11551
+ redirectUrl,
11552
+ clientMetadata: { client_name: oauth?.clientName ?? CLIENT_NAME2 },
11553
+ clientMetadataDocument: cimdFn2,
11554
+ clientId: oauth?.clientId,
11555
+ clientSecret: oauth?.clientSecret,
11556
+ store,
11557
+ onRedirect
11558
+ });
11559
+ }
11560
+ var SourceBackedStateStore = class {
11561
+ source;
11562
+ name;
11563
+ serverUrl;
11564
+ constructor(source, name, serverUrl) {
11565
+ this.source = source;
11566
+ this.name = name;
11567
+ this.serverUrl = serverUrl;
11568
+ }
11569
+ async load() {
11570
+ return this.source.load(this.name, this.serverUrl);
11571
+ }
11572
+ async save(state) {
11573
+ await this.source.save(this.name, this.serverUrl, state);
11574
+ }
11575
+ };
11576
+ var SignInCancelledError = class extends Error {
11577
+ constructor() {
11578
+ super("Sign-in cancelled");
11579
+ this.name = "SignInCancelledError";
11580
+ }
11581
+ };
11582
+ function responseFromRedirectUrl(input, state, redirectUrl) {
11583
+ let url;
11584
+ try {
11585
+ url = new URL(input.trim());
11586
+ } catch {
11587
+ throw new Error("Expected the full redirect URL from the browser address bar");
11588
+ }
11589
+ if (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {
11590
+ throw new Error("The redirect URL does not match this sign-in's redirect URI");
11591
+ }
11592
+ const error = url.searchParams.get("error");
11593
+ if (error) throw new Error(url.searchParams.get("error_description") ?? error);
11594
+ if (url.searchParams.get("state") !== state) {
11595
+ throw new Error("The redirect URL belongs to a different sign-in");
11596
+ }
11597
+ const code = url.searchParams.get("code");
11598
+ if (!code) throw new Error("The redirect URL does not contain an authorization code");
11599
+ return { code, iss: url.searchParams.get("iss") ?? void 0 };
11600
+ }
11601
+ async function waitForAuthorizationResponse(callback, state, redirectUrl, prompt, signal) {
11602
+ const controller = new AbortController();
11603
+ const promptSignal = signal ? AbortSignal.any([controller.signal, signal]) : controller.signal;
11604
+ const fromBrowser = callback.waitForCallback(state, redirectUrl.pathname);
11605
+ const fromUser = prompt.promptForRedirectUrl(promptSignal).then((input) => {
11606
+ if (!input?.trim()) throw new SignInCancelledError();
11607
+ return responseFromRedirectUrl(input, state, redirectUrl);
11608
+ });
11609
+ try {
11610
+ return await Promise.race([fromBrowser, fromUser]);
11611
+ } finally {
11612
+ controller.abort();
11613
+ fromBrowser.catch(() => void 0);
11614
+ fromUser.catch(() => void 0);
11615
+ }
11616
+ }
11617
+ function mergeScopes(...scopes) {
11618
+ const merged = [...new Set(scopes.flatMap((s) => s?.split(/\s+/).filter(Boolean) ?? []))];
11619
+ return merged.length > 0 ? merged.join(" ") : void 0;
11620
+ }
11621
+ async function signIn(options) {
11622
+ const { name, serverUrl, source, oauth, prompt, platform: platform2, signal } = options;
11623
+ if (signal?.aborted) throw new SignInCancelledError();
11624
+ const store = new SourceBackedStateStore(source, name, serverUrl);
11625
+ const stored = await store.load();
11626
+ const cbSettings = callbackSettings(oauth);
11627
+ const registered = stored?.clientInformation && "redirect_uris" in stored.clientInformation ? stored.clientInformation.redirect_uris : [];
11628
+ const preferredPort = cbSettings.port ?? (registered[0] ? Number(new URL(registered[0]).port) || void 0 : void 0);
11629
+ const callback = await OAuthCallbackServer.listen({
11630
+ host: cbSettings.host,
11631
+ redirectHost: cbSettings.redirectHost,
11632
+ port: preferredPort ?? 0,
11633
+ path: cbSettings.path
11634
+ });
11635
+ const redirectUrl = cbSettings.fixedRedirectUrl ?? callback.redirectUrl;
11636
+ try {
11637
+ if (stored) {
11638
+ const next = { ...stored };
11639
+ delete next.oauthState;
11640
+ const hasCimd = buildClientMetadataDocumentFn(oauth, redirectUrl) !== void 0;
11641
+ const keepClient = oauth?.clientId || (hasCimd ? !stored.clientInformation : registered.includes(redirectUrl));
11642
+ if (!keepClient) {
11643
+ delete next.clientInformation;
11644
+ delete next.tokens;
11645
+ delete next.tokensExpireAt;
11646
+ }
11647
+ await store.save(next);
11648
+ }
11649
+ let authorizationUrl;
11650
+ const provider = createProvider(serverUrl, store, oauth, redirectUrl, (url) => {
11651
+ authorizationUrl = url;
11652
+ });
11653
+ const flow = {
11654
+ serverUrl,
11655
+ fetch: timedFetch2(platform2.fetch),
11656
+ signal,
11657
+ authorizationServerMetadataUrl: oauth?.authServerMetadataUrl ? new URL(oauth.authServerMetadataUrl) : void 0,
11658
+ scope: mergeScopes(
11659
+ oauth?.scope,
11660
+ options.stepUp ? stepUpScope(stored?.tokens?.scope, options.scope) : options.scope
11661
+ )
11662
+ };
11663
+ const skipRefresh = options.stepUp === true;
11664
+ if (await authorizeMcp(provider, { ...flow, skipRefresh }) === "AUTHORIZED") return;
11665
+ if (!authorizationUrl) throw new Error("OAuth flow did not produce an authorization URL");
11666
+ const state = await provider.state();
11667
+ const authRedirectUrl = new URL(
11668
+ authorizationUrl.searchParams.get("redirect_uri") ?? redirectUrl
11669
+ );
11670
+ prompt.showAuthorizationUrl(authorizationUrl);
11671
+ const { code, iss } = await waitForAuthorizationResponse(
11672
+ callback,
11673
+ state,
11674
+ authRedirectUrl,
11675
+ prompt,
11676
+ signal
11677
+ );
11678
+ await authorizeMcp(provider, { ...flow, authorizationCode: code, iss });
11679
+ } catch (err) {
11680
+ if (signal?.aborted) throw new SignInCancelledError();
11681
+ throw err;
11682
+ } finally {
11683
+ await callback.close();
11684
+ }
11685
+ }
11686
+
11687
+ // src/auth/token-source.ts
11688
+ function mcpNamespace(server) {
11689
+ return `mcp__${server.replace(/-/g, "_")}`;
11690
+ }
11691
+ function storeKey(name, serverUrl) {
11692
+ const ns = mcpNamespace(name);
11693
+ const url = String(new URL(serverUrl));
11694
+ return `${ns}|${url}`;
11695
+ }
11696
+ function isKernel(platform2) {
11697
+ return platform2.kind === "kernel";
11698
+ }
11699
+
11700
+ // src/auth/pi-store.ts
11701
+ var AUTH_FILE = "mcp-auth.json";
11702
+ var FILE_MODE = 384;
11703
+ function parseStates(raw) {
11704
+ if (!raw?.trim()) return {};
11705
+ const parsed = JSON.parse(raw);
11706
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
11707
+ }
11708
+ function serializeStates(states) {
11709
+ return `${JSON.stringify(states, null, 2)}
11710
+ `;
11711
+ }
11712
+ function legacyKey(serverUrl) {
11713
+ return String(new URL(serverUrl));
11714
+ }
11715
+ var PiFileTokenSource = class {
11716
+ platform;
11717
+ authPath;
11718
+ dirPath;
11719
+ constructor(platform2) {
11720
+ this.platform = platform2;
11721
+ this.dirPath = userConfigDir(platform2);
11722
+ this.authPath = `${this.dirPath}/${AUTH_FILE}`;
11723
+ }
11724
+ get path() {
11725
+ return this.authPath;
11726
+ }
11727
+ async getToken(name, serverUrl) {
11728
+ const state = await this.load(name, serverUrl);
11729
+ if (!state?.tokens?.access_token) return void 0;
11730
+ return {
11731
+ accessToken: state.tokens.access_token,
11732
+ expiresAt: state.tokensExpireAt
11733
+ };
11734
+ }
11735
+ async load(name, serverUrl) {
11736
+ const key = storeKey(name, serverUrl);
11737
+ const legacy = legacyKey(serverUrl);
11738
+ const release = await this.acquireLock();
11739
+ try {
11740
+ const raw = await this.readRaw();
11741
+ const states = parseStates(raw);
11742
+ if (states[key]) return states[key];
11743
+ if (states[legacy]) {
11744
+ states[key] = states[legacy];
11745
+ delete states[legacy];
11746
+ await this.writeStates(states);
11747
+ return states[key];
11748
+ }
11749
+ return void 0;
11750
+ } finally {
11751
+ await release();
11752
+ }
11753
+ }
11754
+ async save(name, serverUrl, state) {
11755
+ const key = storeKey(name, serverUrl);
11756
+ const release = await this.acquireLock();
11757
+ try {
11758
+ const raw = await this.readRaw();
11759
+ const states = parseStates(raw);
11760
+ states[key] = state;
11761
+ await this.writeStates(states);
11762
+ } finally {
11763
+ await release();
11764
+ }
11765
+ }
11766
+ async remove(name, serverUrl) {
11767
+ const key = storeKey(name, serverUrl);
11768
+ const legacy = legacyKey(serverUrl);
11769
+ const release = await this.acquireLock();
11770
+ try {
11771
+ const raw = await this.readRaw();
11772
+ const states = parseStates(raw);
11773
+ const stored = key in states ? key : legacy in states ? legacy : void 0;
11774
+ if (!stored) return false;
11775
+ delete states[stored];
11776
+ await this.writeStates(states);
11777
+ return true;
11778
+ } finally {
11779
+ await release();
11780
+ }
11781
+ }
11782
+ async acquireLock() {
11783
+ await this.ensureDir();
11784
+ return acquireLock(this.platform.fs, this.authPath);
11785
+ }
11786
+ async ensureDir() {
11787
+ try {
11788
+ await this.platform.fs.mkdir(this.dirPath);
11789
+ } catch {
11790
+ }
11791
+ }
11792
+ async readRaw() {
11793
+ try {
11794
+ const data = await this.platform.fs.readFile(this.authPath);
11795
+ return new TextDecoder().decode(data);
11796
+ } catch {
11797
+ return void 0;
11798
+ }
11799
+ }
11800
+ async writeStates(states) {
11801
+ await this.platform.fs.writeFile(this.authPath, serializeStates(states), { mode: FILE_MODE });
11802
+ }
11803
+ };
11804
+
11805
+ // src/cli/auth-verbs.ts
11806
+ function createTokenSource(platform2) {
11807
+ return new PiFileTokenSource(platform2);
11808
+ }
11809
+ function resolveServerName(target) {
11810
+ try {
11811
+ const u = new URL(target.startsWith("http") ? target : `https://${target}`);
11812
+ if (target.includes(".") || target.includes(":")) {
11813
+ return { name: `url:${u.origin}${u.pathname}`, isUrl: true };
11814
+ }
11815
+ } catch {
11816
+ }
11817
+ return { name: target, isUrl: false };
11818
+ }
11819
+ async function resolveLoginTarget(platform2, target) {
11820
+ const config = await MergedConfigSource.load(platform2);
11821
+ const entry = config.entry(target);
11822
+ if (entry && "url" in entry.config && entry.config.url) {
11823
+ const httpConfig = entry.config;
11824
+ return {
11825
+ name: target,
11826
+ serverUrl: httpConfig.url,
11827
+ oauth: httpConfig.oauth
11828
+ };
11829
+ }
11830
+ const resolved = resolveServerName(target);
11831
+ if (resolved.isUrl) {
11832
+ const url = target.startsWith("http") ? target : `https://${target}`;
11833
+ return { name: resolved.name, serverUrl: url, oauth: void 0 };
11834
+ }
11835
+ throw new Error(`unknown target '${target}': not a URL and not found in mcp.json`);
11836
+ }
11837
+ async function runLogin(platform2, args, source) {
11838
+ if (isKernel(platform2)) {
11839
+ await platform2.write(
11840
+ 2,
11841
+ "mcpcat: login is not available in seven. Use the agent's MCP sign-in in Settings, or run mcpcat login on the host.\n"
11842
+ );
11843
+ return 4;
11844
+ }
11845
+ const noBrowser = args.includes("--no-browser");
11846
+ const positional = args.filter((a) => !a.startsWith("-"));
11847
+ if (positional.length === 0) {
11848
+ await platform2.write(2, "mcpcat: login requires a target\n");
11849
+ return 2;
11850
+ }
11851
+ const target = positional[0];
11852
+ let resolved;
11853
+ try {
11854
+ resolved = await resolveLoginTarget(platform2, target);
11855
+ } catch (err) {
11856
+ await platform2.write(2, `mcpcat: ${err.message}
11857
+ `);
11858
+ return 2;
11859
+ }
11860
+ try {
11861
+ await signIn({
11862
+ name: resolved.name,
11863
+ serverUrl: resolved.serverUrl,
11864
+ source,
11865
+ oauth: resolved.oauth,
11866
+ platform: platform2,
11867
+ prompt: {
11868
+ showAuthorizationUrl(url) {
11869
+ if (!noBrowser && platform2.openUrl) {
11870
+ platform2.openUrl(url.href).catch(() => {
11871
+ });
11872
+ }
11873
+ void platform2.write(2, `Open this URL to sign in:
11874
+ ${url.href}
11875
+ `);
11876
+ if (noBrowser || !platform2.openUrl) {
11877
+ void platform2.write(2, "\nPaste the redirect URL from your browser address bar:\n");
11878
+ }
11879
+ },
11880
+ async promptForRedirectUrl(signal) {
11881
+ if (!noBrowser && platform2.openUrl) {
11882
+ return new Promise((_resolve, reject) => {
11883
+ signal.addEventListener("abort", () => reject(new SignInCancelledError()));
11884
+ });
11885
+ }
11886
+ const reader = platform2.stdin.getReader();
11887
+ const chunks = [];
11888
+ try {
11889
+ while (true) {
11890
+ const read = reader.read();
11891
+ const result = await Promise.race([
11892
+ read,
11893
+ new Promise((_, reject) => {
11894
+ signal.addEventListener("abort", () => reject(new SignInCancelledError()));
11895
+ })
11896
+ ]);
11897
+ if (result.done) break;
11898
+ chunks.push(result.value);
11899
+ const text = new TextDecoder().decode(concatUint8Arrays(chunks));
11900
+ if (text.includes("\n")) return text.trim();
11901
+ }
11902
+ } finally {
11903
+ reader.releaseLock();
11904
+ }
11905
+ return new TextDecoder().decode(concatUint8Arrays(chunks)).trim() || void 0;
11906
+ }
11907
+ }
11908
+ });
11909
+ await platform2.write(1, `Signed in to ${target}
11910
+ `);
11911
+ return 0;
11912
+ } catch (err) {
11913
+ if (err instanceof SignInCancelledError) {
11914
+ await platform2.write(2, "mcpcat: sign-in cancelled\n");
11915
+ return 1;
11916
+ }
11917
+ await platform2.write(2, `mcpcat: login failed: ${err.message}
11918
+ `);
11919
+ return 4;
11920
+ }
11921
+ }
11922
+ async function runLogout(platform2, args, source) {
11923
+ if (isKernel(platform2)) {
11924
+ await platform2.write(2, "mcpcat: logout is not available in seven.\n");
11925
+ return 4;
11926
+ }
11927
+ const positional = args.filter((a) => !a.startsWith("-"));
11928
+ if (positional.length === 0) {
11929
+ await platform2.write(2, "mcpcat: logout requires a target\n");
11930
+ return 2;
11931
+ }
11932
+ const target = positional[0];
11933
+ let resolved;
11934
+ try {
11935
+ resolved = await resolveLoginTarget(platform2, target);
11936
+ } catch (err) {
11937
+ await platform2.write(2, `mcpcat: ${err.message}
11938
+ `);
11939
+ return 2;
11940
+ }
11941
+ const removed = await source.remove(resolved.name, resolved.serverUrl);
11942
+ if (removed) {
11943
+ await platform2.write(1, `Signed out of ${target}
11944
+ `);
11945
+ } else {
11946
+ await platform2.write(1, `No credentials stored for ${target}
11947
+ `);
11948
+ }
11949
+ return 0;
11950
+ }
11951
+ function concatUint8Arrays(arrays) {
11952
+ const total = arrays.reduce((s, a) => s + a.length, 0);
11953
+ const result = new Uint8Array(total);
11954
+ let offset = 0;
11955
+ for (const a of arrays) {
11956
+ result.set(a, offset);
11957
+ offset += a.length;
11958
+ }
11959
+ return result;
11960
+ }
11961
+
10577
11962
  // src/config/import.ts
10578
11963
  function isRecord5(value) {
10579
11964
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -11517,16 +12902,7 @@ var CONFIG_VERBS = {
11517
12902
  exposure: true,
11518
12903
  import: true
11519
12904
  };
11520
- var UNIMPLEMENTED_VERBS = /* @__PURE__ */ new Set([
11521
- "resources",
11522
- "read",
11523
- "prompts",
11524
- "prompt",
11525
- "complete",
11526
- "task",
11527
- "login",
11528
- "logout"
11529
- ]);
12905
+ var UNIMPLEMENTED_VERBS = /* @__PURE__ */ new Set(["resources", "read", "prompts", "prompt", "complete", "task"]);
11530
12906
  var CLIENT_VERBS = /* @__PURE__ */ new Set(["info", "tools", "call", "describe", "serve"]);
11531
12907
  function helpText(version) {
11532
12908
  return `mcpcat ${version} \u2013 a curl for the Model Context Protocol
@@ -11550,8 +12926,8 @@ Configuration verbs:
11550
12926
  enable|disable <name> Toggle a server
11551
12927
  exposure <name> <mode> Set exposure mode
11552
12928
  import <file> Import from other configs
11553
- login <target> OAuth sign-in (not implemented yet)
11554
- logout <target> Remove tokens (not implemented yet)
12929
+ login <target> OAuth sign-in
12930
+ logout <target> Remove stored tokens
11555
12931
 
11556
12932
  Server and code verbs:
11557
12933
  serve [--stdio|--http] \u2026 Expose commands or proxy upstream as MCP server
@@ -12142,6 +13518,14 @@ async function run(platform2, version, args) {
12142
13518
  }
12143
13519
  const discResult = await dispatchDiscoveryVerb(platform2, parsed, args);
12144
13520
  if (discResult !== void 0) return discResult;
13521
+ if (parsed.verb === "login") {
13522
+ const source = createTokenSource(platform2);
13523
+ return runLogin(platform2, args.slice(1), source);
13524
+ }
13525
+ if (parsed.verb === "logout") {
13526
+ const source = createTokenSource(platform2);
13527
+ return runLogout(platform2, args.slice(1), source);
13528
+ }
12145
13529
  if (UNIMPLEMENTED_VERBS.has(parsed.verb)) {
12146
13530
  await platform2.write(2, `mcpcat: '${parsed.verb}' is not implemented yet
12147
13531
  `);
@@ -12190,6 +13574,17 @@ function classifyError(err) {
12190
13574
  if (err instanceof McpAuthError) {
12191
13575
  return { code: EXIT_AUTH, kind: "auth", msg: err.message };
12192
13576
  }
13577
+ if (err instanceof AuthStepUpError) {
13578
+ const scopeHint = err.scope ? ` --scope ${err.scope}` : "";
13579
+ return {
13580
+ code: EXIT_AUTH,
13581
+ kind: "auth",
13582
+ msg: `insufficient scope. Run: mcpcat login ${err.target ?? "<target>"}${scopeHint}`
13583
+ };
13584
+ }
13585
+ if (err.name === "McpOAuthAuthorizationRequiredError" || err.name === "McpAuthRequiredError") {
13586
+ return { code: EXIT_AUTH, kind: "auth", msg: err.message };
13587
+ }
12193
13588
  if (err instanceof McpcatError) {
12194
13589
  return { code: err.exitCode, kind: "error", msg: err.message };
12195
13590
  }
@@ -12200,6 +13595,14 @@ function classifyError(err) {
12200
13595
  }
12201
13596
  return { code: EXIT_RPC_ERROR, kind: "rpc_error", msg };
12202
13597
  }
13598
+ function resolveAuthProvider(platform2, hasAuthHeader, url, target, config) {
13599
+ if (hasAuthHeader || !url) return void 0;
13600
+ const source = createTokenSource(platform2);
13601
+ const entry = config.entry(target);
13602
+ const oauth = entry && "url" in entry.config ? entry.config.oauth : void 0;
13603
+ const name = entry ? target : `url:${new URL(url).origin}${new URL(url).pathname}`;
13604
+ return createMcpAuthProvider({ name, serverUrl: url, source, oauth, platform: platform2 });
13605
+ }
12203
13606
  async function runClientVerb(platform2, version, parsed) {
12204
13607
  const { expanded, secrets } = expandAndCollect(parsed.headers, platform2.env);
12205
13608
  const verbose = createVerboseLogger(platform2, parsed.verbose);
@@ -12229,6 +13632,8 @@ async function runClientVerb(platform2, version, parsed) {
12229
13632
  await writeErr(platform2, parsed.jsonOutput, "usage", err.message);
12230
13633
  return EXIT_USAGE;
12231
13634
  }
13635
+ const hasAuthHeader = "Authorization" in expanded;
13636
+ const authProvider = resolveAuthProvider(platform2, hasAuthHeader, resolved.url, target, config);
12232
13637
  let conn;
12233
13638
  try {
12234
13639
  conn = await connect(platform2, {
@@ -12238,11 +13643,22 @@ async function runClientVerb(platform2, version, parsed) {
12238
13643
  version,
12239
13644
  timeoutMs,
12240
13645
  signal: sigintController.signal,
12241
- verbose
13646
+ verbose,
13647
+ authProvider
12242
13648
  });
12243
13649
  } catch (err) {
12244
- if (err instanceof McpAuthError) {
12245
- await writeErr(platform2, parsed.jsonOutput, "auth", err.message);
13650
+ if (err instanceof McpAuthError || err instanceof AuthStepUpError) {
13651
+ const e = classifyError(err);
13652
+ await writeErr(platform2, parsed.jsonOutput, e.kind, e.msg);
13653
+ return EXIT_AUTH;
13654
+ }
13655
+ if (err.name === "McpOAuthAuthorizationRequiredError" || err.name === "McpAuthRequiredError") {
13656
+ await writeErr(
13657
+ platform2,
13658
+ parsed.jsonOutput,
13659
+ "auth",
13660
+ `unauthorized. Run: mcpcat login ${target}`
13661
+ );
12246
13662
  return EXIT_AUTH;
12247
13663
  }
12248
13664
  const msg = transportHint(err) ?? `connection failed: ${err.message}`;
@@ -12389,7 +13805,7 @@ async function main(ctx) {
12389
13805
  packageDir: "/node_modules/@ai-ecoverse/mcpcat"
12390
13806
  });
12391
13807
  const args = ctx.argv.slice(1);
12392
- return run(platform2, "0.9.0", args);
13808
+ return run(platform2, "0.10.0", args);
12393
13809
  }
12394
13810
  export {
12395
13811
  main as default