@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.
@@ -5489,6 +5489,176 @@ function mergeArgs(base, flags) {
5489
5489
  return result;
5490
5490
  }
5491
5491
 
5492
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/callback.js
5493
+ import { createServer } from "node:http";
5494
+ function plainText(page) {
5495
+ if (page.ok)
5496
+ return "Authorization complete. You may close this window.";
5497
+ return page.details ? `${page.message}
5498
+
5499
+ ${page.details}` : page.message;
5500
+ }
5501
+ var OAuthCallbackServer = class _OAuthCallbackServer {
5502
+ redirectUrl;
5503
+ server;
5504
+ paths;
5505
+ timeoutMs;
5506
+ renderPage;
5507
+ pending = /* @__PURE__ */ new Map();
5508
+ constructor(server, redirectUrl, paths, timeoutMs, renderPage) {
5509
+ this.server = server;
5510
+ this.redirectUrl = redirectUrl;
5511
+ this.paths = paths;
5512
+ this.timeoutMs = timeoutMs;
5513
+ this.renderPage = renderPage;
5514
+ }
5515
+ static async listen(options = {}) {
5516
+ const host = options.host ?? "127.0.0.1";
5517
+ const redirectHost = options.redirectHost ?? host;
5518
+ const path = options.path ?? "/callback";
5519
+ let instance;
5520
+ const server = createServer((request, response) => instance?.handle(request.url ?? "/", response));
5521
+ await new Promise((resolve, reject) => {
5522
+ server.once("error", reject);
5523
+ server.listen(options.port ?? 0, host, () => {
5524
+ server.off("error", reject);
5525
+ resolve();
5526
+ });
5527
+ });
5528
+ const address = server.address();
5529
+ if (!address || typeof address === "string")
5530
+ throw new Error("OAuth callback server did not bind to TCP");
5531
+ instance = new _OAuthCallbackServer(server, `http://${redirectHost.includes(":") ? `[${redirectHost}]` : redirectHost}:${address.port}${path}`, [path, ...options.extraPaths ?? []], options.timeoutMs ?? 5 * 6e4, options.renderPage);
5532
+ return instance;
5533
+ }
5534
+ /**
5535
+ * Wait for the authorization response with `state`. With `path`, a response on another path fails, so
5536
+ * a server-specific redirect URI can tell authorization servers apart (RFC 9700 section 4.4.2.2).
5537
+ */
5538
+ waitForCallback(state, path) {
5539
+ if (this.pending.has(state))
5540
+ throw new Error("OAuth state is already pending");
5541
+ return new Promise((resolve, reject) => {
5542
+ const timer = setTimeout(() => {
5543
+ this.pending.delete(state);
5544
+ reject(new Error("OAuth callback timed out"));
5545
+ }, this.timeoutMs);
5546
+ this.pending.set(state, { resolve, reject, timer, path });
5547
+ });
5548
+ }
5549
+ async close() {
5550
+ for (const pending of this.pending.values()) {
5551
+ clearTimeout(pending.timer);
5552
+ pending.reject(new Error("OAuth callback server closed"));
5553
+ }
5554
+ this.pending.clear();
5555
+ await new Promise((resolve, reject) => {
5556
+ this.server.close((error) => error ? reject(error) : resolve());
5557
+ });
5558
+ }
5559
+ reply(response, status, page) {
5560
+ if (this.renderPage) {
5561
+ response.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
5562
+ response.end(this.renderPage(page));
5563
+ } else {
5564
+ response.writeHead(status, { "content-type": "text/plain; charset=utf-8" }).end(plainText(page));
5565
+ }
5566
+ }
5567
+ handle(rawUrl, response) {
5568
+ const url = new URL(rawUrl, this.redirectUrl);
5569
+ if (!this.paths.includes(url.pathname)) {
5570
+ this.reply(response, 404, { ok: false, message: "Not found" });
5571
+ return;
5572
+ }
5573
+ const state = url.searchParams.get("state");
5574
+ const pending = state ? this.pending.get(state) : void 0;
5575
+ if (!state || !pending) {
5576
+ this.reply(response, 400, { ok: false, message: "Invalid or expired OAuth state" });
5577
+ return;
5578
+ }
5579
+ clearTimeout(pending.timer);
5580
+ this.pending.delete(state);
5581
+ if (pending.path !== void 0 && url.pathname !== pending.path) {
5582
+ pending.reject(new Error("The authorization response arrived on another redirect URI"));
5583
+ this.reply(response, 400, { ok: false, message: "Unexpected redirect URI" });
5584
+ return;
5585
+ }
5586
+ const error = url.searchParams.get("error");
5587
+ if (error) {
5588
+ const description = url.searchParams.get("error_description") ?? error;
5589
+ pending.reject(new Error(description));
5590
+ this.reply(response, 200, {
5591
+ ok: false,
5592
+ message: "Authorization failed. You may close this window.",
5593
+ details: description
5594
+ });
5595
+ return;
5596
+ }
5597
+ const code2 = url.searchParams.get("code");
5598
+ if (!code2) {
5599
+ pending.reject(new Error("OAuth callback did not include an authorization code"));
5600
+ this.reply(response, 400, { ok: false, message: "Missing authorization code" });
5601
+ return;
5602
+ }
5603
+ const iss = url.searchParams.get("iss");
5604
+ pending.resolve({ code: code2, state, ...iss ? { iss } : {} });
5605
+ this.reply(response, 200, { ok: true });
5606
+ }
5607
+ };
5608
+
5609
+ // node_modules/@earendil-works/pi-mcp/dist/protocol/types.js
5610
+ var LATEST_PROTOCOL_VERSION = "2025-11-25";
5611
+ var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05"];
5612
+
5613
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/errors.js
5614
+ var OAuthError = class extends Error {
5615
+ code;
5616
+ errorUri;
5617
+ constructor(code2, message, errorUri) {
5618
+ super(message || code2);
5619
+ this.name = "OAuthError";
5620
+ this.code = code2;
5621
+ this.errorUri = errorUri;
5622
+ }
5623
+ };
5624
+ var OAuthIssuerMismatchError = class extends Error {
5625
+ /** `undefined` when no authorization server metadata was discovered. */
5626
+ expected;
5627
+ /** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */
5628
+ received;
5629
+ constructor(expected, received) {
5630
+ const format = (issuer) => issuer === void 0 ? "none" : JSON.stringify(issuer);
5631
+ super(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`);
5632
+ this.name = "OAuthIssuerMismatchError";
5633
+ this.expected = expected;
5634
+ this.received = received;
5635
+ }
5636
+ };
5637
+ var OAuthInsecureEndpointError = class extends Error {
5638
+ endpoint;
5639
+ constructor(endpoint) {
5640
+ super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`);
5641
+ this.name = "OAuthInsecureEndpointError";
5642
+ this.endpoint = endpoint;
5643
+ }
5644
+ };
5645
+ var OAuthRegistrationError = class extends Error {
5646
+ status;
5647
+ body;
5648
+ constructor(status, body) {
5649
+ super(`OAuth dynamic client registration failed with status ${status}: ${body}`);
5650
+ this.name = "OAuthRegistrationError";
5651
+ this.status = status;
5652
+ this.body = body;
5653
+ }
5654
+ };
5655
+ var McpOAuthAuthorizationRequiredError = class extends Error {
5656
+ constructor() {
5657
+ super("MCP OAuth authorization requires user interaction");
5658
+ this.name = "McpOAuthAuthorizationRequiredError";
5659
+ }
5660
+ };
5661
+
5492
5662
  // node_modules/@earendil-works/pi-mcp/dist/protocol/jsonrpc.js
5493
5663
  var JSON_RPC_ERROR_CODES = {
5494
5664
  parseError: -32700,
@@ -5557,9 +5727,726 @@ function parseJsonRpcMessage(value) {
5557
5727
  throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest, "Invalid JSON-RPC message");
5558
5728
  }
5559
5729
 
5560
- // node_modules/@earendil-works/pi-mcp/dist/protocol/types.js
5561
- var LATEST_PROTOCOL_VERSION = "2025-11-25";
5562
- var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05"];
5730
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/types.js
5731
+ function object(value, name) {
5732
+ if (!isObject(value))
5733
+ throw new Error(`Invalid ${name}`);
5734
+ return value;
5735
+ }
5736
+ function compact(value) {
5737
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
5738
+ }
5739
+ function requiredString(value, name) {
5740
+ if (typeof value !== "string" || value.length === 0)
5741
+ throw new Error(`Invalid ${name}`);
5742
+ return value;
5743
+ }
5744
+ function absent(value) {
5745
+ return value === void 0 || value === null || value === "";
5746
+ }
5747
+ function optionalString(value, name) {
5748
+ if (absent(value))
5749
+ return void 0;
5750
+ return requiredString(value, name);
5751
+ }
5752
+ function optionalStrings(value, name) {
5753
+ if (value === void 0 || value === null)
5754
+ return void 0;
5755
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string"))
5756
+ throw new Error(`Invalid ${name}`);
5757
+ return [...value];
5758
+ }
5759
+ function safeUrl(value, name) {
5760
+ const text = requiredString(value, name);
5761
+ if (!URL.canParse(text))
5762
+ throw new Error(`Invalid ${name}`);
5763
+ const url = new URL(text);
5764
+ if (["javascript:", "data:", "vbscript:"].includes(url.protocol))
5765
+ throw new Error(`Invalid ${name}`);
5766
+ return text;
5767
+ }
5768
+ function optionalUrl(value, name) {
5769
+ return absent(value) ? void 0 : safeUrl(value, name);
5770
+ }
5771
+ function parseProtectedResourceMetadata(value) {
5772
+ const input = object(value, "OAuth protected resource metadata");
5773
+ return compact({
5774
+ ...input,
5775
+ resource: safeUrl(input.resource, "OAuth protected resource metadata resource"),
5776
+ authorization_servers: optionalStrings(input.authorization_servers, "authorization_servers")?.map((url) => safeUrl(url, "authorization server URL")),
5777
+ scopes_supported: optionalStrings(input.scopes_supported, "scopes_supported")
5778
+ });
5779
+ }
5780
+ function parseAuthorizationServerMetadata(value) {
5781
+ const input = object(value, "authorization server metadata");
5782
+ const responseTypes = optionalStrings(input.response_types_supported, "response_types_supported");
5783
+ if (!responseTypes)
5784
+ throw new Error("Invalid response_types_supported");
5785
+ return compact({
5786
+ ...input,
5787
+ issuer: safeUrl(input.issuer, "authorization server issuer"),
5788
+ authorization_endpoint: safeUrl(input.authorization_endpoint, "authorization endpoint"),
5789
+ token_endpoint: safeUrl(input.token_endpoint, "token endpoint"),
5790
+ registration_endpoint: optionalUrl(input.registration_endpoint, "registration endpoint"),
5791
+ scopes_supported: optionalStrings(input.scopes_supported, "scopes_supported"),
5792
+ response_types_supported: responseTypes,
5793
+ grant_types_supported: optionalStrings(input.grant_types_supported, "grant_types_supported"),
5794
+ token_endpoint_auth_methods_supported: optionalStrings(input.token_endpoint_auth_methods_supported, "token_endpoint_auth_methods_supported"),
5795
+ code_challenge_methods_supported: optionalStrings(input.code_challenge_methods_supported, "code_challenge_methods_supported"),
5796
+ client_id_metadata_document_supported: typeof input.client_id_metadata_document_supported === "boolean" ? input.client_id_metadata_document_supported : void 0,
5797
+ authorization_response_iss_parameter_supported: typeof input.authorization_response_iss_parameter_supported === "boolean" ? input.authorization_response_iss_parameter_supported : void 0
5798
+ });
5799
+ }
5800
+ function parseOAuthTokens(value) {
5801
+ const input = object(value, "OAuth token response");
5802
+ const expires = absent(input.expires_in) ? void 0 : Number(input.expires_in);
5803
+ if (expires !== void 0 && !Number.isFinite(expires))
5804
+ throw new Error("Invalid expires_in");
5805
+ return compact({
5806
+ access_token: requiredString(input.access_token, "access_token"),
5807
+ token_type: requiredString(input.token_type, "token_type"),
5808
+ expires_in: expires,
5809
+ scope: optionalString(input.scope, "scope"),
5810
+ refresh_token: optionalString(input.refresh_token, "refresh_token"),
5811
+ id_token: optionalString(input.id_token, "id_token")
5812
+ });
5813
+ }
5814
+ function parseClientInformation(value) {
5815
+ const input = object(value, "OAuth client registration response");
5816
+ return compact({
5817
+ ...input,
5818
+ client_id: requiredString(input.client_id, "client_id"),
5819
+ client_secret: optionalString(input.client_secret, "client_secret"),
5820
+ client_id_issued_at: typeof input.client_id_issued_at === "number" ? input.client_id_issued_at : void 0,
5821
+ client_secret_expires_at: typeof input.client_secret_expires_at === "number" ? input.client_secret_expires_at : void 0,
5822
+ redirect_uris: optionalStrings(input.redirect_uris, "redirect_uris") ?? []
5823
+ });
5824
+ }
5825
+
5826
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/discovery.js
5827
+ function discard(response) {
5828
+ void response?.body?.cancel().catch(() => {
5829
+ });
5830
+ }
5831
+ function isDiscoveryMiss(status) {
5832
+ return status >= 400 && status < 500 || status === 502;
5833
+ }
5834
+ function pathSuffix(pathname) {
5835
+ return pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
5836
+ }
5837
+ function field(header, name) {
5838
+ const match = header.match(new RegExp(String.raw`(?:^|[,\s])${name}=(?:"([^"]*)"|([^\s,]+))`, "i"));
5839
+ return match?.[1] || match?.[2] || void 0;
5840
+ }
5841
+ function parseWwwAuthenticate(header) {
5842
+ if (!header)
5843
+ return {};
5844
+ const scheme = header.trimStart().split(/\s+/, 1)[0]?.toLowerCase();
5845
+ if (scheme !== "bearer" && scheme !== "dpop")
5846
+ return {};
5847
+ const resourceMetadata = field(header, "resource_metadata");
5848
+ let resourceMetadataUrl;
5849
+ if (resourceMetadata) {
5850
+ try {
5851
+ resourceMetadataUrl = new URL(resourceMetadata);
5852
+ } catch {
5853
+ }
5854
+ }
5855
+ return {
5856
+ resourceMetadataUrl,
5857
+ scope: field(header, "scope"),
5858
+ error: field(header, "error"),
5859
+ errorDescription: field(header, "error_description")
5860
+ };
5861
+ }
5862
+ async function fetchMetadata(url, fetch, protocolVersion, signal) {
5863
+ return fetch(url, {
5864
+ headers: { Accept: "application/json", "MCP-Protocol-Version": protocolVersion },
5865
+ signal
5866
+ });
5867
+ }
5868
+ async function discoverProtectedResourceMetadata(serverUrl, options = {}) {
5869
+ const server = new URL(serverUrl);
5870
+ const fetch = options.fetch ?? globalThis.fetch;
5871
+ const version = options.protocolVersion ?? LATEST_PROTOCOL_VERSION;
5872
+ 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);
5873
+ if (!options.resourceMetadataUrl && server.pathname !== "/" && isDiscoveryMiss(response.status)) {
5874
+ discard(response);
5875
+ response = await fetchMetadata(new URL("/.well-known/oauth-protected-resource", server.origin), fetch, version, options.signal);
5876
+ }
5877
+ if (!response.ok) {
5878
+ discard(response);
5879
+ throw new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);
5880
+ }
5881
+ return parseProtectedResourceMetadata(await response.json());
5882
+ }
5883
+ function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl) {
5884
+ const issuer = new URL(authorizationServerUrl);
5885
+ const path = pathSuffix(issuer.pathname);
5886
+ const urls = [
5887
+ { url: new URL(`/.well-known/oauth-authorization-server${path}`, issuer.origin), type: "oauth" },
5888
+ { url: new URL(`/.well-known/openid-configuration${path}`, issuer.origin), type: "oidc" }
5889
+ ];
5890
+ if (path)
5891
+ urls.push({ url: new URL(`${path}/.well-known/openid-configuration`, issuer.origin), type: "oidc" });
5892
+ return urls;
5893
+ }
5894
+ async function discoverAuthorizationServerMetadata(authorizationServerUrl, options = {}) {
5895
+ const fetch = options.fetch ?? globalThis.fetch;
5896
+ for (const { url } of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)) {
5897
+ const response = await fetchMetadata(url, fetch, options.protocolVersion ?? LATEST_PROTOCOL_VERSION, options.signal);
5898
+ if (!response.ok) {
5899
+ discard(response);
5900
+ if (isDiscoveryMiss(response.status))
5901
+ continue;
5902
+ throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);
5903
+ }
5904
+ const metadata = parseAuthorizationServerMetadata(await response.json());
5905
+ if (!options.skipIssuerValidation) {
5906
+ const expected = String(authorizationServerUrl);
5907
+ const trim = (value) => value.endsWith("/") ? value.slice(0, -1) : value;
5908
+ if (trim(metadata.issuer) !== trim(expected))
5909
+ throw new OAuthIssuerMismatchError(expected, metadata.issuer);
5910
+ }
5911
+ return metadata;
5912
+ }
5913
+ return void 0;
5914
+ }
5915
+ async function discoverOAuthServerInfo(serverUrl, options = {}) {
5916
+ let resourceMetadata;
5917
+ try {
5918
+ resourceMetadata = await discoverProtectedResourceMetadata(serverUrl, {
5919
+ resourceMetadataUrl: options.resourceMetadataUrl,
5920
+ fetch: options.fetch,
5921
+ signal: options.signal
5922
+ });
5923
+ } catch (error) {
5924
+ if (error instanceof TypeError)
5925
+ throw error;
5926
+ }
5927
+ if (options.authorizationServerMetadataUrl) {
5928
+ const url = options.authorizationServerMetadataUrl;
5929
+ const response = await fetchMetadata(url, options.fetch ?? globalThis.fetch, LATEST_PROTOCOL_VERSION, options.signal);
5930
+ if (!response.ok) {
5931
+ discard(response);
5932
+ throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);
5933
+ }
5934
+ const metadata = parseAuthorizationServerMetadata(await response.json());
5935
+ return { authorizationServerUrl: metadata.issuer, authorizationServerMetadata: metadata, resourceMetadata };
5936
+ }
5937
+ const authorizationServerUrl = resourceMetadata?.authorization_servers?.[0] ?? String(new URL("/", serverUrl));
5938
+ return {
5939
+ authorizationServerUrl,
5940
+ authorizationServerMetadata: await discoverAuthorizationServerMetadata(authorizationServerUrl, {
5941
+ fetch: options.fetch,
5942
+ skipIssuerValidation: options.skipIssuerValidation,
5943
+ signal: options.signal
5944
+ }),
5945
+ resourceMetadata
5946
+ };
5947
+ }
5948
+ function resourceUrlFromServerUrl(value) {
5949
+ const url = new URL(value);
5950
+ url.hash = "";
5951
+ return url;
5952
+ }
5953
+ function selectResource(serverUrl, metadata) {
5954
+ if (!metadata)
5955
+ return void 0;
5956
+ const requested = resourceUrlFromServerUrl(serverUrl);
5957
+ const configured = new URL(metadata.resource);
5958
+ if (requested.origin !== configured.origin) {
5959
+ throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);
5960
+ }
5961
+ const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : `${requested.pathname}/`;
5962
+ const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : `${configured.pathname}/`;
5963
+ if (!requestedPath.startsWith(configuredPath)) {
5964
+ throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);
5965
+ }
5966
+ return metadata.resource;
5967
+ }
5968
+
5969
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/flow.js
5970
+ function loopback(hostname) {
5971
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
5972
+ }
5973
+ function applicationType(redirectUris) {
5974
+ const native = redirectUris.some((uri) => {
5975
+ if (!URL.canParse(uri))
5976
+ return false;
5977
+ const url = new URL(uri);
5978
+ return url.protocol !== "http:" && url.protocol !== "https:" || loopback(url.hostname);
5979
+ });
5980
+ return native ? "native" : "web";
5981
+ }
5982
+ function secureEndpoint(value) {
5983
+ const url = new URL(value);
5984
+ if (url.protocol !== "https:" && !loopback(url.hostname))
5985
+ throw new OAuthInsecureEndpointError(url.href);
5986
+ return url;
5987
+ }
5988
+ function selectClientAuthMethod(information, supported) {
5989
+ const hinted = "token_endpoint_auth_method" in information ? information.token_endpoint_auth_method : void 0;
5990
+ if (hinted && ["client_secret_basic", "client_secret_post", "none"].includes(hinted) && (supported.length === 0 || supported.includes(hinted))) {
5991
+ return hinted;
5992
+ }
5993
+ if (supported.length === 0)
5994
+ return information.client_secret ? "client_secret_basic" : "none";
5995
+ if (information.client_secret && supported.includes("client_secret_basic"))
5996
+ return "client_secret_basic";
5997
+ if (information.client_secret && supported.includes("client_secret_post"))
5998
+ return "client_secret_post";
5999
+ if (supported.includes("none"))
6000
+ return "none";
6001
+ return information.client_secret ? "client_secret_post" : "none";
6002
+ }
6003
+ function applyClientAuthentication(method, information, headers, params) {
6004
+ if (method === "client_secret_basic") {
6005
+ if (!information.client_secret)
6006
+ throw new Error("client_secret_basic requires a client secret");
6007
+ headers.set("Authorization", `Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`);
6008
+ } else {
6009
+ params.set("client_id", information.client_id);
6010
+ if (method === "client_secret_post" && information.client_secret)
6011
+ params.set("client_secret", information.client_secret);
6012
+ }
6013
+ }
6014
+ async function pkce() {
6015
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
6016
+ const verifier = Buffer.from(bytes).toString("base64url");
6017
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
6018
+ return { verifier, challenge: Buffer.from(digest).toString("base64url") };
6019
+ }
6020
+ async function startAuthorization(authorizationServerUrl, options) {
6021
+ const metadata = options.metadata;
6022
+ if (metadata && !metadata.response_types_supported.includes("code")) {
6023
+ throw new Error("Authorization server does not support authorization codes");
6024
+ }
6025
+ if (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes("S256")) {
6026
+ throw new Error("Authorization server does not support PKCE S256");
6027
+ }
6028
+ const url = new URL(metadata?.authorization_endpoint ?? new URL("/authorize", authorizationServerUrl));
6029
+ const { verifier, challenge } = await pkce();
6030
+ url.searchParams.set("response_type", "code");
6031
+ url.searchParams.set("client_id", options.clientInformation.client_id);
6032
+ url.searchParams.set("code_challenge", challenge);
6033
+ url.searchParams.set("code_challenge_method", "S256");
6034
+ url.searchParams.set("redirect_uri", String(options.redirectUrl));
6035
+ if (options.state)
6036
+ url.searchParams.set("state", options.state);
6037
+ if (options.scope)
6038
+ url.searchParams.set("scope", options.scope);
6039
+ if (options.scope?.split(/\s+/).includes("offline_access"))
6040
+ url.searchParams.set("prompt", "consent");
6041
+ if (options.resource)
6042
+ url.searchParams.set("resource", options.resource);
6043
+ return { authorizationUrl: url, codeVerifier: verifier };
6044
+ }
6045
+ async function tokenRequest(authorizationServerUrl, options, params) {
6046
+ const url = secureEndpoint(options.metadata?.token_endpoint ?? new URL("/token", authorizationServerUrl));
6047
+ const headers = new Headers({ Accept: "application/json", "content-type": "application/x-www-form-urlencoded" });
6048
+ if (options.resource)
6049
+ params.set("resource", options.resource);
6050
+ if (options.addClientAuthentication) {
6051
+ await options.addClientAuthentication(headers, params, url, options.metadata);
6052
+ } else {
6053
+ applyClientAuthentication(selectClientAuthMethod(options.clientInformation, options.metadata?.token_endpoint_auth_methods_supported ?? []), options.clientInformation, headers, params);
6054
+ }
6055
+ const response = await (options.fetch ?? globalThis.fetch)(url, {
6056
+ method: "POST",
6057
+ headers,
6058
+ body: params,
6059
+ signal: options.signal
6060
+ });
6061
+ const text = await response.text();
6062
+ let value;
6063
+ try {
6064
+ value = JSON.parse(text);
6065
+ } catch {
6066
+ }
6067
+ if (isObject(value) && typeof value.error === "string") {
6068
+ 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);
6069
+ }
6070
+ if (!response.ok)
6071
+ throw new OAuthError("server_error", `HTTP ${response.status}: ${text}`);
6072
+ return parseOAuthTokens(value);
6073
+ }
6074
+ async function registerClient(authorizationServerUrl, options) {
6075
+ const endpoint = options.metadata?.registration_endpoint;
6076
+ if (options.metadata && !endpoint)
6077
+ throw new Error("Authorization server does not support dynamic client registration");
6078
+ const response = await (options.fetch ?? globalThis.fetch)(new URL(endpoint ?? new URL("/register", authorizationServerUrl)), {
6079
+ method: "POST",
6080
+ headers: { Accept: "application/json", "content-type": "application/json" },
6081
+ body: JSON.stringify({
6082
+ ...options.clientMetadata,
6083
+ application_type: options.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),
6084
+ ...options.scope ? { scope: options.scope } : {}
6085
+ }),
6086
+ signal: options.signal
6087
+ });
6088
+ if (!response.ok)
6089
+ throw new OAuthRegistrationError(response.status, await response.text());
6090
+ return parseClientInformation(await response.json());
6091
+ }
6092
+ async function exchangeAuthorizationCode(authorizationServerUrl, options) {
6093
+ return tokenRequest(authorizationServerUrl, options, new URLSearchParams({
6094
+ grant_type: "authorization_code",
6095
+ code: options.code,
6096
+ code_verifier: options.codeVerifier,
6097
+ redirect_uri: String(options.redirectUrl)
6098
+ }));
6099
+ }
6100
+ async function refreshAuthorization(authorizationServerUrl, options) {
6101
+ const tokens = await tokenRequest(authorizationServerUrl, options, new URLSearchParams({ grant_type: "refresh_token", refresh_token: options.refreshToken }));
6102
+ return { refresh_token: options.refreshToken, ...tokens };
6103
+ }
6104
+ function withScope(tokens, scope) {
6105
+ return tokens.scope === void 0 && scope ? { ...tokens, scope } : tokens;
6106
+ }
6107
+ function stepUpScope(granted, challenged) {
6108
+ if (!challenged)
6109
+ return void 0;
6110
+ const scopes = [granted, challenged].flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []);
6111
+ return [...new Set(scopes)].join(" ");
6112
+ }
6113
+ async function runFlow(provider, options) {
6114
+ const metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);
6115
+ const cached = metadataUrl ? void 0 : await provider.discoveryState?.();
6116
+ const discovered = cached?.authorizationServerUrl ? {
6117
+ authorizationServerUrl: cached.authorizationServerUrl,
6118
+ authorizationServerMetadata: cached.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {
6119
+ fetch: options.fetch,
6120
+ skipIssuerValidation: options.skipIssuerValidation,
6121
+ signal: options.signal
6122
+ }),
6123
+ resourceMetadata: cached.resourceMetadata
6124
+ } : await discoverOAuthServerInfo(options.serverUrl, {
6125
+ resourceMetadataUrl: options.resourceMetadataUrl,
6126
+ authorizationServerMetadataUrl: metadataUrl,
6127
+ fetch: options.fetch,
6128
+ skipIssuerValidation: options.skipIssuerValidation,
6129
+ signal: options.signal
6130
+ });
6131
+ if (!metadataUrl) {
6132
+ await provider.saveDiscoveryState?.({
6133
+ ...discovered,
6134
+ ...options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}
6135
+ });
6136
+ }
6137
+ const metadata = discovered.authorizationServerMetadata;
6138
+ const resource = selectResource(options.serverUrl, discovered.resourceMetadata);
6139
+ const scope = options.scope || discovered.resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
6140
+ const stored = await provider.clientInformation();
6141
+ const clientDocument = stored ? void 0 : provider.clientMetadataDocument?.(metadata);
6142
+ if (clientDocument) {
6143
+ const url = new URL(clientDocument.url);
6144
+ if (url.protocol !== "https:" || url.pathname === "/")
6145
+ throw new Error("Invalid OAuth client metadata URL");
6146
+ }
6147
+ let client = stored ?? (clientDocument && { client_id: clientDocument.url });
6148
+ if (!client) {
6149
+ if (options.authorizationCode)
6150
+ throw new Error("OAuth client information is missing during code exchange");
6151
+ if (!provider.saveClientInformation)
6152
+ throw new Error("OAuth client information cannot be persisted");
6153
+ client = await registerClient(discovered.authorizationServerUrl, {
6154
+ metadata,
6155
+ clientMetadata: provider.clientMetadata,
6156
+ scope,
6157
+ fetch: options.fetch,
6158
+ signal: options.signal
6159
+ });
6160
+ await provider.saveClientInformation(client);
6161
+ }
6162
+ const redirectUrl = clientDocument?.redirectUrl ?? provider.redirectUrl;
6163
+ const tokenOptions = {
6164
+ metadata,
6165
+ clientInformation: client,
6166
+ resource,
6167
+ addClientAuthentication: provider.addClientAuthentication,
6168
+ fetch: options.fetch,
6169
+ signal: options.signal
6170
+ };
6171
+ if (options.authorizationCode) {
6172
+ const iss = options.iss;
6173
+ if (iss !== void 0 || metadata?.authorization_response_iss_parameter_supported) {
6174
+ if (iss !== metadata?.issuer)
6175
+ throw new OAuthIssuerMismatchError(metadata?.issuer, iss);
6176
+ }
6177
+ const tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {
6178
+ ...tokenOptions,
6179
+ code: options.authorizationCode,
6180
+ codeVerifier: await provider.codeVerifier(),
6181
+ redirectUrl
6182
+ });
6183
+ await provider.saveTokens(withScope(tokens, scope));
6184
+ return "AUTHORIZED";
6185
+ }
6186
+ const existing = options.skipRefresh ? void 0 : await provider.tokens();
6187
+ if (existing?.refresh_token) {
6188
+ try {
6189
+ const tokens = await refreshAuthorization(discovered.authorizationServerUrl, {
6190
+ ...tokenOptions,
6191
+ refreshToken: existing.refresh_token
6192
+ });
6193
+ await provider.saveTokens(withScope(tokens, existing.scope));
6194
+ return "AUTHORIZED";
6195
+ } catch (error) {
6196
+ if (options.signal?.aborted || error instanceof OAuthInsecureEndpointError)
6197
+ throw error;
6198
+ if (error instanceof OAuthError && error.code !== "server_error")
6199
+ throw error;
6200
+ }
6201
+ }
6202
+ const state = await provider.state?.();
6203
+ const authorization = await startAuthorization(discovered.authorizationServerUrl, {
6204
+ metadata,
6205
+ clientInformation: client,
6206
+ redirectUrl,
6207
+ scope,
6208
+ state,
6209
+ resource
6210
+ });
6211
+ await provider.saveCodeVerifier(authorization.codeVerifier);
6212
+ await provider.redirectToAuthorization(authorization.authorizationUrl);
6213
+ return "REDIRECT";
6214
+ }
6215
+ async function authorizeMcp(provider, options) {
6216
+ try {
6217
+ return await runFlow(provider, options);
6218
+ } catch (error) {
6219
+ if (error instanceof OAuthError && ["invalid_client", "unauthorized_client"].includes(error.code)) {
6220
+ await provider.invalidateCredentials?.("all");
6221
+ return runFlow(provider, options);
6222
+ }
6223
+ if (error instanceof OAuthError && error.code === "invalid_grant") {
6224
+ await provider.invalidateCredentials?.("tokens");
6225
+ return runFlow(provider, options);
6226
+ }
6227
+ throw error;
6228
+ }
6229
+ }
6230
+
6231
+ // node_modules/@earendil-works/pi-mcp/dist/oauth/provider.js
6232
+ var MemoryOAuthStateStore = class {
6233
+ value;
6234
+ load() {
6235
+ return this.value === void 0 ? void 0 : structuredClone(this.value);
6236
+ }
6237
+ save(state) {
6238
+ this.value = structuredClone(state);
6239
+ }
6240
+ };
6241
+ var McpOAuthProvider = class {
6242
+ redirectUrl;
6243
+ clientMetadata;
6244
+ clientMetadataDocument;
6245
+ serverUrl;
6246
+ configuredClient;
6247
+ store;
6248
+ onRedirect;
6249
+ writes = Promise.resolve();
6250
+ constructor(options) {
6251
+ this.serverUrl = String(new URL(options.serverUrl));
6252
+ this.redirectUrl = String(options.redirectUrl);
6253
+ this.clientMetadata = {
6254
+ ...options.clientMetadata,
6255
+ redirect_uris: options.clientMetadata.redirect_uris ?? [this.redirectUrl],
6256
+ grant_types: options.clientMetadata.grant_types ?? ["authorization_code", "refresh_token"],
6257
+ response_types: options.clientMetadata.response_types ?? ["code"],
6258
+ token_endpoint_auth_method: options.clientMetadata.token_endpoint_auth_method ?? (options.clientSecret ? "client_secret_post" : "none")
6259
+ };
6260
+ this.clientMetadataDocument = options.clientMetadataDocument;
6261
+ this.configuredClient = options.clientId ? { client_id: options.clientId, ...options.clientSecret ? { client_secret: options.clientSecret } : {} } : void 0;
6262
+ this.store = options.store ?? new MemoryOAuthStateStore();
6263
+ this.onRedirect = options.onRedirect;
6264
+ }
6265
+ async state() {
6266
+ const existing = (await this.load()).oauthState;
6267
+ if (existing)
6268
+ return existing;
6269
+ const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");
6270
+ await this.update((value) => ({ ...value, oauthState: state }));
6271
+ return state;
6272
+ }
6273
+ async clientInformation() {
6274
+ return this.configuredClient ?? (await this.load()).clientInformation;
6275
+ }
6276
+ async saveClientInformation(information) {
6277
+ if (this.configuredClient)
6278
+ return;
6279
+ await this.update((value) => ({ ...value, clientInformation: information }));
6280
+ }
6281
+ async tokens() {
6282
+ return (await this.load()).tokens;
6283
+ }
6284
+ async saveTokens(tokens) {
6285
+ const expiresAt = tokens.expires_in === void 0 ? void 0 : Date.now() + tokens.expires_in * 1e3;
6286
+ await this.update((value) => {
6287
+ const next = { ...value, tokens };
6288
+ if (expiresAt === void 0)
6289
+ delete next.tokensExpireAt;
6290
+ else
6291
+ next.tokensExpireAt = expiresAt;
6292
+ return next;
6293
+ });
6294
+ }
6295
+ async redirectToAuthorization(url) {
6296
+ await this.onRedirect(url);
6297
+ }
6298
+ async saveCodeVerifier(verifier) {
6299
+ await this.update((value) => ({ ...value, codeVerifier: verifier }));
6300
+ }
6301
+ async codeVerifier() {
6302
+ const verifier = (await this.load()).codeVerifier;
6303
+ if (!verifier)
6304
+ throw new Error("No OAuth PKCE code verifier is stored");
6305
+ return verifier;
6306
+ }
6307
+ async invalidateCredentials(kind) {
6308
+ await this.update((value) => {
6309
+ const next = { ...value };
6310
+ if (kind === "all" || kind === "client")
6311
+ delete next.clientInformation;
6312
+ if (kind === "all" || kind === "tokens") {
6313
+ delete next.tokens;
6314
+ delete next.tokensExpireAt;
6315
+ }
6316
+ if (kind === "all" || kind === "verifier")
6317
+ delete next.codeVerifier;
6318
+ if (kind === "all" || kind === "discovery")
6319
+ delete next.discovery;
6320
+ if (kind === "all")
6321
+ delete next.oauthState;
6322
+ return next;
6323
+ });
6324
+ }
6325
+ async saveDiscoveryState(discovery) {
6326
+ await this.update((value) => ({ ...value, discovery }));
6327
+ }
6328
+ async discoveryState() {
6329
+ return (await this.load()).discovery;
6330
+ }
6331
+ async load() {
6332
+ await this.writes;
6333
+ return this.own(await this.store.load());
6334
+ }
6335
+ async update(update) {
6336
+ this.writes = this.writes.then(async () => {
6337
+ await this.store.save(update(this.own(await this.store.load())));
6338
+ });
6339
+ await this.writes;
6340
+ }
6341
+ /** Stored state for another server URL is ignored so credentials never leak across servers. */
6342
+ own(state) {
6343
+ return state?.serverUrl === this.serverUrl ? state : { serverUrl: this.serverUrl };
6344
+ }
6345
+ };
6346
+
6347
+ // src/auth/auth-provider.ts
6348
+ var CIMD_URL = "https://mcpcat.sliccy.ai/oauth/client.json";
6349
+ var CLIENT_NAME = "mcpcat";
6350
+ var CALLBACK_HOST = "127.0.0.1";
6351
+ var CALLBACK_PATH = "/callback";
6352
+ var REQUEST_TIMEOUT_MS = 15e3;
6353
+ var REFRESH_SKEW_MS = 3e4;
6354
+ var FALLBACK_REDIRECT_URL = `http://${CALLBACK_HOST}${CALLBACK_PATH}`;
6355
+ function timedFetch(fetchImpl) {
6356
+ return (input, init) => {
6357
+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
6358
+ return fetchImpl(input, {
6359
+ ...init,
6360
+ signal: init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout
6361
+ });
6362
+ };
6363
+ }
6364
+ var SourceBackedStore = class {
6365
+ source;
6366
+ name;
6367
+ serverUrl;
6368
+ constructor(source, name, serverUrl) {
6369
+ this.source = source;
6370
+ this.name = name;
6371
+ this.serverUrl = serverUrl;
6372
+ }
6373
+ async load() {
6374
+ return this.source.load(this.name, this.serverUrl);
6375
+ }
6376
+ async save(state) {
6377
+ await this.source.save(this.name, this.serverUrl, state);
6378
+ }
6379
+ };
6380
+ function cimdFn(redirectUrl) {
6381
+ return (metadata) => {
6382
+ if (!metadata?.client_id_metadata_document_supported) return void 0;
6383
+ if (!metadata.token_endpoint_auth_methods_supported?.includes("none")) return void 0;
6384
+ if (!metadata.authorization_response_iss_parameter_supported) return void 0;
6385
+ return { url: CIMD_URL, redirectUrl };
6386
+ };
6387
+ }
6388
+ var AuthStepUpError = class extends Error {
6389
+ scope;
6390
+ target;
6391
+ constructor(scope, target) {
6392
+ super(scope ? `insufficient_scope: ${scope}` : "insufficient_scope");
6393
+ this.name = "AuthStepUpError";
6394
+ this.scope = scope;
6395
+ this.target = target;
6396
+ }
6397
+ };
6398
+ function createMcpAuthProvider(options) {
6399
+ const { name, serverUrl, source, oauth, platform: platform2 } = options;
6400
+ const store = new SourceBackedStore(source, name, serverUrl);
6401
+ let refreshing;
6402
+ const refresh = async (staleToken) => {
6403
+ refreshing ??= (async () => {
6404
+ const state = await store.load();
6405
+ if (state?.tokens?.access_token !== staleToken) return;
6406
+ if (!state?.tokens?.refresh_token) throw new McpOAuthAuthorizationRequiredError();
6407
+ const registered = state.clientInformation && "redirect_uris" in state.clientInformation ? state.clientInformation.redirect_uris : [];
6408
+ const redirectUrl = registered[0] ?? FALLBACK_REDIRECT_URL;
6409
+ const provider = new McpOAuthProvider({
6410
+ serverUrl,
6411
+ redirectUrl,
6412
+ clientMetadata: { client_name: oauth?.clientName ?? CLIENT_NAME },
6413
+ clientMetadataDocument: oauth?.clientId ? void 0 : cimdFn(redirectUrl),
6414
+ clientId: oauth?.clientId,
6415
+ clientSecret: oauth?.clientSecret,
6416
+ store,
6417
+ onRedirect() {
6418
+ }
6419
+ });
6420
+ const result = await authorizeMcp(provider, {
6421
+ serverUrl,
6422
+ authorizationServerMetadataUrl: oauth?.authServerMetadataUrl ? new URL(oauth.authServerMetadataUrl) : void 0,
6423
+ fetch: timedFetch(platform2.fetch)
6424
+ });
6425
+ if (result === "REDIRECT") throw new McpOAuthAuthorizationRequiredError();
6426
+ })().finally(() => {
6427
+ refreshing = void 0;
6428
+ });
6429
+ return refreshing;
6430
+ };
6431
+ return {
6432
+ async token() {
6433
+ await refreshing?.catch(() => void 0);
6434
+ const state = await store.load();
6435
+ const token = state?.tokens?.access_token;
6436
+ const expired = state?.tokensExpireAt !== void 0 && state.tokensExpireAt - REFRESH_SKEW_MS <= Date.now();
6437
+ if (!expired || !state?.tokens?.refresh_token) return token;
6438
+ await refresh(token).catch(() => void 0);
6439
+ return (await store.load())?.tokens?.access_token;
6440
+ },
6441
+ async onUnauthorized(context) {
6442
+ const challenge = parseWwwAuthenticate(context.response.headers.get("www-authenticate"));
6443
+ if (challenge.error === "insufficient_scope") {
6444
+ throw new AuthStepUpError(challenge.scope, options.name);
6445
+ }
6446
+ await refresh(context.token);
6447
+ }
6448
+ };
6449
+ }
5563
6450
 
5564
6451
  // node_modules/@earendil-works/pi-mcp/dist/client.js
5565
6452
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
@@ -6257,21 +7144,21 @@ async function consumeSseStream(stream, options) {
6257
7144
  if (line.startsWith(":"))
6258
7145
  return;
6259
7146
  const colon = line.indexOf(":");
6260
- const field = colon < 0 ? line : line.slice(0, colon);
7147
+ const field2 = colon < 0 ? line : line.slice(0, colon);
6261
7148
  let value = colon < 0 ? "" : line.slice(colon + 1);
6262
7149
  if (value.startsWith(" "))
6263
7150
  value = value.slice(1);
6264
- if (field === "data") {
7151
+ if (field2 === "data") {
6265
7152
  dataBytes += Buffer.byteLength(value) + (dataLines.length > 0 ? 1 : 0);
6266
7153
  if (dataBytes > maxEventBytes)
6267
7154
  throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);
6268
7155
  dataLines.push(value);
6269
- } else if (field === "event")
7156
+ } else if (field2 === "event")
6270
7157
  eventName = value;
6271
- else if (field === "id" && !value.includes("\0")) {
7158
+ else if (field2 === "id" && !value.includes("\0")) {
6272
7159
  eventId = value;
6273
7160
  options.onId?.(value);
6274
- } else if (field === "retry" && /^\d+$/.test(value))
7161
+ } else if (field2 === "retry" && /^\d+$/.test(value))
6275
7162
  options.onRetry?.(Number(value));
6276
7163
  };
6277
7164
  try {
@@ -6334,7 +7221,7 @@ function needsAuthorization(response) {
6334
7221
  function isTransientStatus(status) {
6335
7222
  return status === 408 || status === 429 || status >= 500;
6336
7223
  }
6337
- function discard(response) {
7224
+ function discard2(response) {
6338
7225
  return response.body?.cancel().catch(() => {
6339
7226
  }) ?? Promise.resolve();
6340
7227
  }
@@ -6385,7 +7272,7 @@ var StreamableHttpTransport = class extends TransportEvents {
6385
7272
  await this.checkResponse(response);
6386
7273
  this.captureSession(response);
6387
7274
  if (!isJsonRpcRequest(message)) {
6388
- await discard(response);
7275
+ await discard2(response);
6389
7276
  if ("method" in message && message.method === "notifications/initialized")
6390
7277
  this.startGetStream();
6391
7278
  return;
@@ -6404,7 +7291,7 @@ var StreamableHttpTransport = class extends TransportEvents {
6404
7291
  void this.consumeResponseStream(response.body, message.id);
6405
7292
  return;
6406
7293
  }
6407
- await discard(response);
7294
+ await discard2(response);
6408
7295
  throw new McpHttpError(response.status, `Unsupported MCP response content type: ${type ?? "missing"}`);
6409
7296
  }
6410
7297
  async close() {
@@ -6419,7 +7306,7 @@ var StreamableHttpTransport = class extends TransportEvents {
6419
7306
  headers: this.buildHeaders({}, this.lastToken),
6420
7307
  signal: AbortSignal.timeout(1e3)
6421
7308
  });
6422
- await discard(response);
7309
+ await discard2(response);
6423
7310
  } catch {
6424
7311
  }
6425
7312
  }
@@ -6450,7 +7337,7 @@ var StreamableHttpTransport = class extends TransportEvents {
6450
7337
  try {
6451
7338
  await onUnauthorized({ response, serverUrl: this.url, fetch: this.fetch, token });
6452
7339
  } finally {
6453
- await discard(response);
7340
+ await discard2(response);
6454
7341
  }
6455
7342
  }
6456
7343
  }
@@ -6607,14 +7494,14 @@ var StreamableHttpTransport = class extends TransportEvents {
6607
7494
  }
6608
7495
  });
6609
7496
  if (response.status === 405) {
6610
- await discard(response);
7497
+ await discard2(response);
6611
7498
  return void 0;
6612
7499
  }
6613
7500
  await this.checkResponse(response);
6614
7501
  this.captureSession(response);
6615
7502
  const type = contentType(response);
6616
7503
  if (type !== "text/event-stream" || !response.body) {
6617
- await discard(response);
7504
+ await discard2(response);
6618
7505
  throw new McpHttpError(response.status, `Unsupported MCP GET response content type: ${type ?? "missing"}`);
6619
7506
  }
6620
7507
  return response.body;
@@ -7085,7 +7972,8 @@ function buildTransport(options) {
7085
7972
  return new StreamableHttpTransport({
7086
7973
  url: options.url,
7087
7974
  headers: options.headers,
7088
- fetch: options.fetchImpl
7975
+ fetch: options.fetchImpl,
7976
+ authProvider: options.authProvider
7089
7977
  });
7090
7978
  }
7091
7979
  if (!options.command) throw new Error("PiConnection requires either a url or a command");
@@ -7197,6 +8085,18 @@ async function connect(platform2, options) {
7197
8085
  });
7198
8086
  }
7199
8087
  if (!options.url) throw new Error("connect requires either a url or a command");
8088
+ if (options.authProvider) {
8089
+ const token = await options.authProvider.token();
8090
+ if (token) {
8091
+ return createPiConnection({
8092
+ url: options.url,
8093
+ headers: options.headers,
8094
+ fetchImpl: platform2.fetch,
8095
+ authProvider: options.authProvider,
8096
+ ...shared
8097
+ });
8098
+ }
8099
+ }
7200
8100
  if (options.protocolVersion && !options.protocolVersion.startsWith("2026")) {
7201
8101
  return createPiConnection({
7202
8102
  url: options.url,
@@ -7223,6 +8123,7 @@ async function connect(platform2, options) {
7223
8123
  url: options.url,
7224
8124
  headers: options.headers,
7225
8125
  fetchImpl: platform2.fetch,
8126
+ authProvider: options.authProvider,
7226
8127
  ...shared
7227
8128
  });
7228
8129
  }
@@ -7697,8 +8598,8 @@ async function formatOutput(platform2, result, json) {
7697
8598
  return result.ok ? 0 : isTimeout ? 124 : 1;
7698
8599
  }
7699
8600
  async function createSandbox(platform2, tools, globals, timeoutMs) {
7700
- const isKernel = platform2.packageDir !== void 0;
7701
- if (isKernel) {
8601
+ const isKernel2 = platform2.packageDir !== void 0;
8602
+ if (isKernel2) {
7702
8603
  const { InlineCodemodeSandbox: InlineCodemodeSandbox2 } = await Promise.resolve().then(() => (init_portable(), portable_exports));
7703
8604
  const wasm = await loadWasmKernel(platform2);
7704
8605
  return new InlineCodemodeSandbox2({ tools, globals, timeoutMs, wasm });
@@ -7823,8 +8724,8 @@ function resolveAliases(value) {
7823
8724
  }
7824
8725
  return out;
7825
8726
  }
7826
- function fail(server, message, field) {
7827
- return { server, ...field ? { field } : {}, message };
8727
+ function fail(server, message, field2) {
8728
+ return { server, ...field2 ? { field: field2 } : {}, message };
7828
8729
  }
7829
8730
  function validateCommon(name, value) {
7830
8731
  const exposures = EXPOSURES.map((e) => `"${e}"`).join(", ");
@@ -9245,7 +10146,7 @@ function argvForCommand(command, args2) {
9245
10146
  if (args2.error) return { error: args2.error };
9246
10147
  const argv = [...command.path];
9247
10148
  for (const positional of command.positionals) {
9248
- const found = args2.fields.find((field) => field.name === positional.name);
10149
+ const found = args2.fields.find((field2) => field2.name === positional.name);
9249
10150
  if (!found) {
9250
10151
  if (positional.required) return { error: `missing ${positional.name}` };
9251
10152
  continue;
@@ -9264,7 +10165,7 @@ function argvForCommand(command, args2) {
9264
10165
  function appendFlags(flags, fields) {
9265
10166
  const argv = [];
9266
10167
  for (const flag of flags) {
9267
- const found = fields.find((field) => field.name === flag.name);
10168
+ const found = fields.find((field2) => field2.name === flag.name);
9268
10169
  if (!found || found.value === false) continue;
9269
10170
  const encoded = encodeFlag(flag, found.value);
9270
10171
  if ("error" in encoded) return encoded;
@@ -10973,6 +11874,478 @@ async function handleMcpRequest(request, tools, call, serverName, version, allow
10973
11874
  };
10974
11875
  }
10975
11876
 
11877
+ // src/auth/oauth.ts
11878
+ var CALLBACK_HOST2 = "127.0.0.1";
11879
+ var CALLBACK_PATH2 = "/callback";
11880
+ var CIMD_URL2 = "https://mcpcat.sliccy.ai/oauth/client.json";
11881
+ var CLIENT_NAME2 = "mcpcat";
11882
+ var REQUEST_TIMEOUT_MS2 = 15e3;
11883
+ function timedFetch2(fetchImpl) {
11884
+ return (input, init) => {
11885
+ const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS2);
11886
+ return fetchImpl(input, {
11887
+ ...init,
11888
+ signal: init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout
11889
+ });
11890
+ };
11891
+ }
11892
+ function callbackSettings(oauth) {
11893
+ const raw = oauth?.callbackUrl ?? `http://${CALLBACK_HOST2}${CALLBACK_PATH2}`;
11894
+ const url = new URL(raw);
11895
+ const address = url.hostname.replace(/^\[|\]$/g, "");
11896
+ const port = url.port ? Number(url.port) : oauth?.callbackPort;
11897
+ let fixedRedirectUrl;
11898
+ if (url.port) fixedRedirectUrl = oauth?.callbackUrl;
11899
+ else if (port !== void 0) {
11900
+ url.port = String(port);
11901
+ fixedRedirectUrl = url.href;
11902
+ }
11903
+ return {
11904
+ host: address === "localhost" ? CALLBACK_HOST2 : address,
11905
+ redirectHost: address,
11906
+ port,
11907
+ path: url.pathname,
11908
+ fixedRedirectUrl
11909
+ };
11910
+ }
11911
+ function cimdForServer(metadata, redirectUrl) {
11912
+ if (!metadata?.client_id_metadata_document_supported) return void 0;
11913
+ if (!metadata.token_endpoint_auth_methods_supported?.includes("none")) return void 0;
11914
+ if (!metadata.authorization_response_iss_parameter_supported) return void 0;
11915
+ return {
11916
+ url: CIMD_URL2,
11917
+ redirectUrl
11918
+ };
11919
+ }
11920
+ function buildClientMetadataDocumentFn(oauth, redirectUrl) {
11921
+ if (oauth?.clientRegistration === "dcr") return void 0;
11922
+ if (oauth?.clientId) return void 0;
11923
+ return (metadata) => {
11924
+ if (oauth?.clientRegistration === "cimd") {
11925
+ if (!metadata?.client_id_metadata_document_supported || !metadata.token_endpoint_auth_methods_supported?.includes("none")) {
11926
+ return void 0;
11927
+ }
11928
+ if (!metadata.authorization_response_iss_parameter_supported) return void 0;
11929
+ return { url: CIMD_URL2, redirectUrl };
11930
+ }
11931
+ return cimdForServer(metadata, redirectUrl);
11932
+ };
11933
+ }
11934
+ function createProvider(serverUrl, store, oauth, redirectUrl, onRedirect) {
11935
+ const cimdFn2 = buildClientMetadataDocumentFn(oauth, redirectUrl);
11936
+ return new McpOAuthProvider({
11937
+ serverUrl,
11938
+ redirectUrl,
11939
+ clientMetadata: { client_name: oauth?.clientName ?? CLIENT_NAME2 },
11940
+ clientMetadataDocument: cimdFn2,
11941
+ clientId: oauth?.clientId,
11942
+ clientSecret: oauth?.clientSecret,
11943
+ store,
11944
+ onRedirect
11945
+ });
11946
+ }
11947
+ var SourceBackedStateStore = class {
11948
+ source;
11949
+ name;
11950
+ serverUrl;
11951
+ constructor(source, name, serverUrl) {
11952
+ this.source = source;
11953
+ this.name = name;
11954
+ this.serverUrl = serverUrl;
11955
+ }
11956
+ async load() {
11957
+ return this.source.load(this.name, this.serverUrl);
11958
+ }
11959
+ async save(state) {
11960
+ await this.source.save(this.name, this.serverUrl, state);
11961
+ }
11962
+ };
11963
+ var SignInCancelledError = class extends Error {
11964
+ constructor() {
11965
+ super("Sign-in cancelled");
11966
+ this.name = "SignInCancelledError";
11967
+ }
11968
+ };
11969
+ function responseFromRedirectUrl(input, state, redirectUrl) {
11970
+ let url;
11971
+ try {
11972
+ url = new URL(input.trim());
11973
+ } catch {
11974
+ throw new Error("Expected the full redirect URL from the browser address bar");
11975
+ }
11976
+ if (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {
11977
+ throw new Error("The redirect URL does not match this sign-in's redirect URI");
11978
+ }
11979
+ const error = url.searchParams.get("error");
11980
+ if (error) throw new Error(url.searchParams.get("error_description") ?? error);
11981
+ if (url.searchParams.get("state") !== state) {
11982
+ throw new Error("The redirect URL belongs to a different sign-in");
11983
+ }
11984
+ const code2 = url.searchParams.get("code");
11985
+ if (!code2) throw new Error("The redirect URL does not contain an authorization code");
11986
+ return { code: code2, iss: url.searchParams.get("iss") ?? void 0 };
11987
+ }
11988
+ async function waitForAuthorizationResponse(callback, state, redirectUrl, prompt, signal) {
11989
+ const controller = new AbortController();
11990
+ const promptSignal = signal ? AbortSignal.any([controller.signal, signal]) : controller.signal;
11991
+ const fromBrowser = callback.waitForCallback(state, redirectUrl.pathname);
11992
+ const fromUser = prompt.promptForRedirectUrl(promptSignal).then((input) => {
11993
+ if (!input?.trim()) throw new SignInCancelledError();
11994
+ return responseFromRedirectUrl(input, state, redirectUrl);
11995
+ });
11996
+ try {
11997
+ return await Promise.race([fromBrowser, fromUser]);
11998
+ } finally {
11999
+ controller.abort();
12000
+ fromBrowser.catch(() => void 0);
12001
+ fromUser.catch(() => void 0);
12002
+ }
12003
+ }
12004
+ function mergeScopes(...scopes) {
12005
+ const merged = [...new Set(scopes.flatMap((s) => s?.split(/\s+/).filter(Boolean) ?? []))];
12006
+ return merged.length > 0 ? merged.join(" ") : void 0;
12007
+ }
12008
+ async function signIn(options) {
12009
+ const { name, serverUrl, source, oauth, prompt, platform: platform2, signal } = options;
12010
+ if (signal?.aborted) throw new SignInCancelledError();
12011
+ const store = new SourceBackedStateStore(source, name, serverUrl);
12012
+ const stored = await store.load();
12013
+ const cbSettings = callbackSettings(oauth);
12014
+ const registered = stored?.clientInformation && "redirect_uris" in stored.clientInformation ? stored.clientInformation.redirect_uris : [];
12015
+ const preferredPort = cbSettings.port ?? (registered[0] ? Number(new URL(registered[0]).port) || void 0 : void 0);
12016
+ const callback = await OAuthCallbackServer.listen({
12017
+ host: cbSettings.host,
12018
+ redirectHost: cbSettings.redirectHost,
12019
+ port: preferredPort ?? 0,
12020
+ path: cbSettings.path
12021
+ });
12022
+ const redirectUrl = cbSettings.fixedRedirectUrl ?? callback.redirectUrl;
12023
+ try {
12024
+ if (stored) {
12025
+ const next = { ...stored };
12026
+ delete next.oauthState;
12027
+ const hasCimd = buildClientMetadataDocumentFn(oauth, redirectUrl) !== void 0;
12028
+ const keepClient = oauth?.clientId || (hasCimd ? !stored.clientInformation : registered.includes(redirectUrl));
12029
+ if (!keepClient) {
12030
+ delete next.clientInformation;
12031
+ delete next.tokens;
12032
+ delete next.tokensExpireAt;
12033
+ }
12034
+ await store.save(next);
12035
+ }
12036
+ let authorizationUrl;
12037
+ const provider = createProvider(serverUrl, store, oauth, redirectUrl, (url) => {
12038
+ authorizationUrl = url;
12039
+ });
12040
+ const flow = {
12041
+ serverUrl,
12042
+ fetch: timedFetch2(platform2.fetch),
12043
+ signal,
12044
+ authorizationServerMetadataUrl: oauth?.authServerMetadataUrl ? new URL(oauth.authServerMetadataUrl) : void 0,
12045
+ scope: mergeScopes(
12046
+ oauth?.scope,
12047
+ options.stepUp ? stepUpScope(stored?.tokens?.scope, options.scope) : options.scope
12048
+ )
12049
+ };
12050
+ const skipRefresh = options.stepUp === true;
12051
+ if (await authorizeMcp(provider, { ...flow, skipRefresh }) === "AUTHORIZED") return;
12052
+ if (!authorizationUrl) throw new Error("OAuth flow did not produce an authorization URL");
12053
+ const state = await provider.state();
12054
+ const authRedirectUrl = new URL(
12055
+ authorizationUrl.searchParams.get("redirect_uri") ?? redirectUrl
12056
+ );
12057
+ prompt.showAuthorizationUrl(authorizationUrl);
12058
+ const { code: code2, iss } = await waitForAuthorizationResponse(
12059
+ callback,
12060
+ state,
12061
+ authRedirectUrl,
12062
+ prompt,
12063
+ signal
12064
+ );
12065
+ await authorizeMcp(provider, { ...flow, authorizationCode: code2, iss });
12066
+ } catch (err) {
12067
+ if (signal?.aborted) throw new SignInCancelledError();
12068
+ throw err;
12069
+ } finally {
12070
+ await callback.close();
12071
+ }
12072
+ }
12073
+
12074
+ // src/auth/token-source.ts
12075
+ function mcpNamespace(server) {
12076
+ return `mcp__${server.replace(/-/g, "_")}`;
12077
+ }
12078
+ function storeKey(name, serverUrl) {
12079
+ const ns = mcpNamespace(name);
12080
+ const url = String(new URL(serverUrl));
12081
+ return `${ns}|${url}`;
12082
+ }
12083
+ function isKernel(platform2) {
12084
+ return platform2.kind === "kernel";
12085
+ }
12086
+
12087
+ // src/auth/pi-store.ts
12088
+ var AUTH_FILE = "mcp-auth.json";
12089
+ var FILE_MODE = 384;
12090
+ function parseStates(raw) {
12091
+ if (!raw?.trim()) return {};
12092
+ const parsed = JSON.parse(raw);
12093
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
12094
+ }
12095
+ function serializeStates(states) {
12096
+ return `${JSON.stringify(states, null, 2)}
12097
+ `;
12098
+ }
12099
+ function legacyKey(serverUrl) {
12100
+ return String(new URL(serverUrl));
12101
+ }
12102
+ var PiFileTokenSource = class {
12103
+ platform;
12104
+ authPath;
12105
+ dirPath;
12106
+ constructor(platform2) {
12107
+ this.platform = platform2;
12108
+ this.dirPath = userConfigDir(platform2);
12109
+ this.authPath = `${this.dirPath}/${AUTH_FILE}`;
12110
+ }
12111
+ get path() {
12112
+ return this.authPath;
12113
+ }
12114
+ async getToken(name, serverUrl) {
12115
+ const state = await this.load(name, serverUrl);
12116
+ if (!state?.tokens?.access_token) return void 0;
12117
+ return {
12118
+ accessToken: state.tokens.access_token,
12119
+ expiresAt: state.tokensExpireAt
12120
+ };
12121
+ }
12122
+ async load(name, serverUrl) {
12123
+ const key = storeKey(name, serverUrl);
12124
+ const legacy = legacyKey(serverUrl);
12125
+ const release = await this.acquireLock();
12126
+ try {
12127
+ const raw = await this.readRaw();
12128
+ const states = parseStates(raw);
12129
+ if (states[key]) return states[key];
12130
+ if (states[legacy]) {
12131
+ states[key] = states[legacy];
12132
+ delete states[legacy];
12133
+ await this.writeStates(states);
12134
+ return states[key];
12135
+ }
12136
+ return void 0;
12137
+ } finally {
12138
+ await release();
12139
+ }
12140
+ }
12141
+ async save(name, serverUrl, state) {
12142
+ const key = storeKey(name, serverUrl);
12143
+ const release = await this.acquireLock();
12144
+ try {
12145
+ const raw = await this.readRaw();
12146
+ const states = parseStates(raw);
12147
+ states[key] = state;
12148
+ await this.writeStates(states);
12149
+ } finally {
12150
+ await release();
12151
+ }
12152
+ }
12153
+ async remove(name, serverUrl) {
12154
+ const key = storeKey(name, serverUrl);
12155
+ const legacy = legacyKey(serverUrl);
12156
+ const release = await this.acquireLock();
12157
+ try {
12158
+ const raw = await this.readRaw();
12159
+ const states = parseStates(raw);
12160
+ const stored = key in states ? key : legacy in states ? legacy : void 0;
12161
+ if (!stored) return false;
12162
+ delete states[stored];
12163
+ await this.writeStates(states);
12164
+ return true;
12165
+ } finally {
12166
+ await release();
12167
+ }
12168
+ }
12169
+ async acquireLock() {
12170
+ await this.ensureDir();
12171
+ return acquireLock(this.platform.fs, this.authPath);
12172
+ }
12173
+ async ensureDir() {
12174
+ try {
12175
+ await this.platform.fs.mkdir(this.dirPath);
12176
+ } catch {
12177
+ }
12178
+ }
12179
+ async readRaw() {
12180
+ try {
12181
+ const data = await this.platform.fs.readFile(this.authPath);
12182
+ return new TextDecoder().decode(data);
12183
+ } catch {
12184
+ return void 0;
12185
+ }
12186
+ }
12187
+ async writeStates(states) {
12188
+ await this.platform.fs.writeFile(this.authPath, serializeStates(states), { mode: FILE_MODE });
12189
+ }
12190
+ };
12191
+
12192
+ // src/cli/auth-verbs.ts
12193
+ function createTokenSource(platform2) {
12194
+ return new PiFileTokenSource(platform2);
12195
+ }
12196
+ function resolveServerName(target) {
12197
+ try {
12198
+ const u = new URL(target.startsWith("http") ? target : `https://${target}`);
12199
+ if (target.includes(".") || target.includes(":")) {
12200
+ return { name: `url:${u.origin}${u.pathname}`, isUrl: true };
12201
+ }
12202
+ } catch {
12203
+ }
12204
+ return { name: target, isUrl: false };
12205
+ }
12206
+ async function resolveLoginTarget(platform2, target) {
12207
+ const config = await MergedConfigSource.load(platform2);
12208
+ const entry = config.entry(target);
12209
+ if (entry && "url" in entry.config && entry.config.url) {
12210
+ const httpConfig = entry.config;
12211
+ return {
12212
+ name: target,
12213
+ serverUrl: httpConfig.url,
12214
+ oauth: httpConfig.oauth
12215
+ };
12216
+ }
12217
+ const resolved = resolveServerName(target);
12218
+ if (resolved.isUrl) {
12219
+ const url = target.startsWith("http") ? target : `https://${target}`;
12220
+ return { name: resolved.name, serverUrl: url, oauth: void 0 };
12221
+ }
12222
+ throw new Error(`unknown target '${target}': not a URL and not found in mcp.json`);
12223
+ }
12224
+ async function runLogin(platform2, args2, source) {
12225
+ if (isKernel(platform2)) {
12226
+ await platform2.write(
12227
+ 2,
12228
+ "mcpcat: login is not available in seven. Use the agent's MCP sign-in in Settings, or run mcpcat login on the host.\n"
12229
+ );
12230
+ return 4;
12231
+ }
12232
+ const noBrowser = args2.includes("--no-browser");
12233
+ const positional = args2.filter((a) => !a.startsWith("-"));
12234
+ if (positional.length === 0) {
12235
+ await platform2.write(2, "mcpcat: login requires a target\n");
12236
+ return 2;
12237
+ }
12238
+ const target = positional[0];
12239
+ let resolved;
12240
+ try {
12241
+ resolved = await resolveLoginTarget(platform2, target);
12242
+ } catch (err) {
12243
+ await platform2.write(2, `mcpcat: ${err.message}
12244
+ `);
12245
+ return 2;
12246
+ }
12247
+ try {
12248
+ await signIn({
12249
+ name: resolved.name,
12250
+ serverUrl: resolved.serverUrl,
12251
+ source,
12252
+ oauth: resolved.oauth,
12253
+ platform: platform2,
12254
+ prompt: {
12255
+ showAuthorizationUrl(url) {
12256
+ if (!noBrowser && platform2.openUrl) {
12257
+ platform2.openUrl(url.href).catch(() => {
12258
+ });
12259
+ }
12260
+ void platform2.write(2, `Open this URL to sign in:
12261
+ ${url.href}
12262
+ `);
12263
+ if (noBrowser || !platform2.openUrl) {
12264
+ void platform2.write(2, "\nPaste the redirect URL from your browser address bar:\n");
12265
+ }
12266
+ },
12267
+ async promptForRedirectUrl(signal) {
12268
+ if (!noBrowser && platform2.openUrl) {
12269
+ return new Promise((_resolve, reject) => {
12270
+ signal.addEventListener("abort", () => reject(new SignInCancelledError()));
12271
+ });
12272
+ }
12273
+ const reader = platform2.stdin.getReader();
12274
+ const chunks = [];
12275
+ try {
12276
+ while (true) {
12277
+ const read = reader.read();
12278
+ const result = await Promise.race([
12279
+ read,
12280
+ new Promise((_, reject) => {
12281
+ signal.addEventListener("abort", () => reject(new SignInCancelledError()));
12282
+ })
12283
+ ]);
12284
+ if (result.done) break;
12285
+ chunks.push(result.value);
12286
+ const text = new TextDecoder().decode(concatUint8Arrays(chunks));
12287
+ if (text.includes("\n")) return text.trim();
12288
+ }
12289
+ } finally {
12290
+ reader.releaseLock();
12291
+ }
12292
+ return new TextDecoder().decode(concatUint8Arrays(chunks)).trim() || void 0;
12293
+ }
12294
+ }
12295
+ });
12296
+ await platform2.write(1, `Signed in to ${target}
12297
+ `);
12298
+ return 0;
12299
+ } catch (err) {
12300
+ if (err instanceof SignInCancelledError) {
12301
+ await platform2.write(2, "mcpcat: sign-in cancelled\n");
12302
+ return 1;
12303
+ }
12304
+ await platform2.write(2, `mcpcat: login failed: ${err.message}
12305
+ `);
12306
+ return 4;
12307
+ }
12308
+ }
12309
+ async function runLogout(platform2, args2, source) {
12310
+ if (isKernel(platform2)) {
12311
+ await platform2.write(2, "mcpcat: logout is not available in seven.\n");
12312
+ return 4;
12313
+ }
12314
+ const positional = args2.filter((a) => !a.startsWith("-"));
12315
+ if (positional.length === 0) {
12316
+ await platform2.write(2, "mcpcat: logout requires a target\n");
12317
+ return 2;
12318
+ }
12319
+ const target = positional[0];
12320
+ let resolved;
12321
+ try {
12322
+ resolved = await resolveLoginTarget(platform2, target);
12323
+ } catch (err) {
12324
+ await platform2.write(2, `mcpcat: ${err.message}
12325
+ `);
12326
+ return 2;
12327
+ }
12328
+ const removed = await source.remove(resolved.name, resolved.serverUrl);
12329
+ if (removed) {
12330
+ await platform2.write(1, `Signed out of ${target}
12331
+ `);
12332
+ } else {
12333
+ await platform2.write(1, `No credentials stored for ${target}
12334
+ `);
12335
+ }
12336
+ return 0;
12337
+ }
12338
+ function concatUint8Arrays(arrays) {
12339
+ const total = arrays.reduce((s, a) => s + a.length, 0);
12340
+ const result = new Uint8Array(total);
12341
+ let offset = 0;
12342
+ for (const a of arrays) {
12343
+ result.set(a, offset);
12344
+ offset += a.length;
12345
+ }
12346
+ return result;
12347
+ }
12348
+
10976
12349
  // src/config/import.ts
10977
12350
  function isRecord5(value) {
10978
12351
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -11916,16 +13289,7 @@ var CONFIG_VERBS = {
11916
13289
  exposure: true,
11917
13290
  import: true
11918
13291
  };
11919
- var UNIMPLEMENTED_VERBS = /* @__PURE__ */ new Set([
11920
- "resources",
11921
- "read",
11922
- "prompts",
11923
- "prompt",
11924
- "complete",
11925
- "task",
11926
- "login",
11927
- "logout"
11928
- ]);
13292
+ var UNIMPLEMENTED_VERBS = /* @__PURE__ */ new Set(["resources", "read", "prompts", "prompt", "complete", "task"]);
11929
13293
  var CLIENT_VERBS = /* @__PURE__ */ new Set(["info", "tools", "call", "describe", "serve"]);
11930
13294
  function helpText(version) {
11931
13295
  return `mcpcat ${version} \u2013 a curl for the Model Context Protocol
@@ -11949,8 +13313,8 @@ Configuration verbs:
11949
13313
  enable|disable <name> Toggle a server
11950
13314
  exposure <name> <mode> Set exposure mode
11951
13315
  import <file> Import from other configs
11952
- login <target> OAuth sign-in (not implemented yet)
11953
- logout <target> Remove tokens (not implemented yet)
13316
+ login <target> OAuth sign-in
13317
+ logout <target> Remove stored tokens
11954
13318
 
11955
13319
  Server and code verbs:
11956
13320
  serve [--stdio|--http] \u2026 Expose commands or proxy upstream as MCP server
@@ -12541,6 +13905,14 @@ async function run(platform2, version, args2) {
12541
13905
  }
12542
13906
  const discResult = await dispatchDiscoveryVerb(platform2, parsed, args2);
12543
13907
  if (discResult !== void 0) return discResult;
13908
+ if (parsed.verb === "login") {
13909
+ const source = createTokenSource(platform2);
13910
+ return runLogin(platform2, args2.slice(1), source);
13911
+ }
13912
+ if (parsed.verb === "logout") {
13913
+ const source = createTokenSource(platform2);
13914
+ return runLogout(platform2, args2.slice(1), source);
13915
+ }
12544
13916
  if (UNIMPLEMENTED_VERBS.has(parsed.verb)) {
12545
13917
  await platform2.write(2, `mcpcat: '${parsed.verb}' is not implemented yet
12546
13918
  `);
@@ -12589,6 +13961,17 @@ function classifyError(err) {
12589
13961
  if (err instanceof McpAuthError) {
12590
13962
  return { code: EXIT_AUTH, kind: "auth", msg: err.message };
12591
13963
  }
13964
+ if (err instanceof AuthStepUpError) {
13965
+ const scopeHint = err.scope ? ` --scope ${err.scope}` : "";
13966
+ return {
13967
+ code: EXIT_AUTH,
13968
+ kind: "auth",
13969
+ msg: `insufficient scope. Run: mcpcat login ${err.target ?? "<target>"}${scopeHint}`
13970
+ };
13971
+ }
13972
+ if (err.name === "McpOAuthAuthorizationRequiredError" || err.name === "McpAuthRequiredError") {
13973
+ return { code: EXIT_AUTH, kind: "auth", msg: err.message };
13974
+ }
12592
13975
  if (err instanceof McpcatError) {
12593
13976
  return { code: err.exitCode, kind: "error", msg: err.message };
12594
13977
  }
@@ -12599,6 +13982,14 @@ function classifyError(err) {
12599
13982
  }
12600
13983
  return { code: EXIT_RPC_ERROR, kind: "rpc_error", msg };
12601
13984
  }
13985
+ function resolveAuthProvider(platform2, hasAuthHeader, url, target, config) {
13986
+ if (hasAuthHeader || !url) return void 0;
13987
+ const source = createTokenSource(platform2);
13988
+ const entry = config.entry(target);
13989
+ const oauth = entry && "url" in entry.config ? entry.config.oauth : void 0;
13990
+ const name = entry ? target : `url:${new URL(url).origin}${new URL(url).pathname}`;
13991
+ return createMcpAuthProvider({ name, serverUrl: url, source, oauth, platform: platform2 });
13992
+ }
12602
13993
  async function runClientVerb(platform2, version, parsed) {
12603
13994
  const { expanded, secrets } = expandAndCollect(parsed.headers, platform2.env);
12604
13995
  const verbose = createVerboseLogger(platform2, parsed.verbose);
@@ -12628,6 +14019,8 @@ async function runClientVerb(platform2, version, parsed) {
12628
14019
  await writeErr(platform2, parsed.jsonOutput, "usage", err.message);
12629
14020
  return EXIT_USAGE;
12630
14021
  }
14022
+ const hasAuthHeader = "Authorization" in expanded;
14023
+ const authProvider = resolveAuthProvider(platform2, hasAuthHeader, resolved.url, target, config);
12631
14024
  let conn;
12632
14025
  try {
12633
14026
  conn = await connect(platform2, {
@@ -12637,11 +14030,22 @@ async function runClientVerb(platform2, version, parsed) {
12637
14030
  version,
12638
14031
  timeoutMs,
12639
14032
  signal: sigintController.signal,
12640
- verbose
14033
+ verbose,
14034
+ authProvider
12641
14035
  });
12642
14036
  } catch (err) {
12643
- if (err instanceof McpAuthError) {
12644
- await writeErr(platform2, parsed.jsonOutput, "auth", err.message);
14037
+ if (err instanceof McpAuthError || err instanceof AuthStepUpError) {
14038
+ const e = classifyError(err);
14039
+ await writeErr(platform2, parsed.jsonOutput, e.kind, e.msg);
14040
+ return EXIT_AUTH;
14041
+ }
14042
+ if (err.name === "McpOAuthAuthorizationRequiredError" || err.name === "McpAuthRequiredError") {
14043
+ await writeErr(
14044
+ platform2,
14045
+ parsed.jsonOutput,
14046
+ "auth",
14047
+ `unauthorized. Run: mcpcat login ${target}`
14048
+ );
12645
14049
  return EXIT_AUTH;
12646
14050
  }
12647
14051
  const msg = transportHint(err) ?? `connection failed: ${err.message}`;
@@ -12677,7 +14081,7 @@ async function writeErr(p, json, kind, msg) {
12677
14081
  import { spawn as cpSpawn } from "node:child_process";
12678
14082
  import { constants } from "node:fs";
12679
14083
  import { access, mkdir, readFile as readFile3, rename, rmdir, stat, writeFile } from "node:fs/promises";
12680
- import { createServer } from "node:net";
14084
+ import { createServer as createServer2 } from "node:net";
12681
14085
  import { Readable, Writable } from "node:stream";
12682
14086
  import * as tty from "node:tty";
12683
14087
  var USE_PROCESS_GROUPS2 = process.platform !== "win32";
@@ -12736,8 +14140,8 @@ var hostFs = {
12736
14140
  async readFile(path) {
12737
14141
  return new Uint8Array(await readFile3(path));
12738
14142
  },
12739
- async writeFile(path, data) {
12740
- await writeFile(path, data);
14143
+ async writeFile(path, data, options) {
14144
+ await writeFile(path, data, options?.mode !== void 0 ? { mode: options.mode } : void 0);
12741
14145
  },
12742
14146
  async mkdir(path) {
12743
14147
  await mkdir(path, { recursive: true });
@@ -12775,7 +14179,7 @@ function createStderrStream() {
12775
14179
  }
12776
14180
  function nodeListen(options) {
12777
14181
  return new Promise((resolve, reject) => {
12778
- const server = createServer();
14182
+ const server = createServer2();
12779
14183
  const pending = [];
12780
14184
  const ready = [];
12781
14185
  let closed = false;
@@ -12873,5 +14277,5 @@ function createHostPlatform() {
12873
14277
  // src/host.ts
12874
14278
  var platform = createHostPlatform();
12875
14279
  var args = process.argv.slice(2);
12876
- var code = await run(platform, "0.9.0", args);
14280
+ var code = await run(platform, "0.10.0", args);
12877
14281
  process.exit(code);