@kya-os/mcp-i-core 1.4.0 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -26,7 +26,7 @@ export type { OAuthServiceConfig } from "./services/oauth-service";
26
26
  export { ToolContextBuilder } from "./services/tool-context-builder";
27
27
  export type { ToolContextBuilderConfig } from "./services/tool-context-builder";
28
28
  export { OAuthProviderRegistry } from "./services/oauth-provider-registry";
29
- export { ProviderResolver, ConsentOnlyModeError, } from "./services/provider-resolver";
29
+ export { ProviderResolver, ConsentOnlyModeError, CredentialAuthModeError, } from "./services/provider-resolver";
30
30
  export { ProviderValidator, ProviderValidationError, } from "./services/provider-validator";
31
31
  export { OAuthTokenRetrievalService } from "./services/oauth-token-retrieval.service";
32
32
  export type { OAuthTokenRetrievalServiceConfig } from "./services/oauth-token-retrieval.service";
@@ -43,6 +43,8 @@ export type { ToolProtection, ToolProtectionConfig, ToolProtectionServiceConfig,
43
43
  export { DelegationRequiredError } from "./types/tool-protection";
44
44
  export { OAuthRequiredError } from "./types/oauth-required-error";
45
45
  export type { OAuthRequiredErrorOptions } from "./types/oauth-required-error";
46
+ export { DelegationErrorFormatter, createDelegationErrorFormatter, } from "./services/delegation-error-formatter";
47
+ export type { DelegationErrorFormatOptions, DelegationErrorResult, ClientMessageTemplate, ClientMessagesConfig, } from "./services/delegation-error-formatter";
46
48
  export { DelegationCredentialIssuer, createDelegationIssuer, type IssueDelegationOptions, type VCSigningFunction, type IdentityProvider as DelegationIdentityProvider, } from "./delegation/vc-issuer";
47
49
  export { DelegationCredentialVerifier, createDelegationVerifier, type DelegationVCVerificationResult, type VerifyDelegationVCOptions, type DIDResolver, type DIDDocument, type VerificationMethod, type StatusListResolver, type SignatureVerificationFunction, } from "./delegation/vc-verifier";
48
50
  export { StatusList2021Manager, createStatusListManager, type StatusListStorageProvider, type StatusListIdentityProvider, } from "./delegation/statuslist-manager";
package/dist/index.js CHANGED
@@ -20,8 +20,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
20
20
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
21
21
  };
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.CascadingRevocationManager = exports.createDelegationGraph = exports.DelegationGraphManager = exports.isIndexSet = exports.BitstringManager = exports.createStatusListManager = exports.StatusList2021Manager = exports.createDelegationVerifier = exports.DelegationCredentialVerifier = exports.createDelegationIssuer = exports.DelegationCredentialIssuer = exports.OAuthRequiredError = exports.DelegationRequiredError = exports.NoOpToolProtectionCache = exports.InMemoryToolProtectionCache = exports.createProofVerificationError = exports.PROOF_VERIFICATION_ERROR_CODES = exports.ProofVerificationError = exports.migrateLegacyKeys = exports.StorageKeyHelpers = exports.createStorageProviders = exports.NoOpOAuthConfigCache = exports.InMemoryOAuthConfigCache = exports.BatchDelegationService = exports.OAuthTokenRetrievalService = exports.ProviderValidationError = exports.ProviderValidator = exports.ConsentOnlyModeError = exports.ProviderResolver = exports.OAuthProviderRegistry = exports.ToolContextBuilder = exports.OAuthService = exports.OAuthConfigService = exports.createSessionRegistrationService = exports.SessionRegistrationService = exports.authorizationMatches = exports.AccessControlApiService = exports.ProofVerifier = exports.CryptoService = exports.ToolProtectionService = exports.MCPIRuntimeBase = exports.MemoryIdentityProvider = exports.MemoryNonceCacheProvider = exports.MemoryStorageProvider = exports.IdentityProvider = exports.NonceCacheProvider = exports.StorageProvider = exports.FetchProvider = exports.ClockProvider = exports.CryptoProvider = void 0;
24
- exports.IdpTokenResolver = exports.UserDidManager = exports.fetchRemoteConfig = exports.bytesToBase64 = exports.base64urlDecodeToString = exports.base64urlDecodeToBytes = exports.base64urlEncodeFromString = exports.base64urlEncodeFromBytes = exports.parseVCJWT = exports.completeVCJWT = exports.createUnsignedVCJWT = exports.canonicalizeJSON = exports.getSchemaStats = exports.getCriticalSchemas = exports.getSchemaById = exports.getSchemasByCategory = exports.getAllSchemas = exports.SCHEMA_REGISTRY = exports.createSchemaVerifier = exports.SchemaVerifier = exports.isValidBase58 = exports.base58Decode = exports.base58Encode = exports.resolveDidKeySync = exports.publicKeyToJwk = exports.extractPublicKeyFromDidKey = exports.isEd25519DidKey = exports.createDidKeyResolver = exports.MemoryDelegationGraphStorage = exports.MemoryStatusListStorage = exports.createCascadingRevocationManager = void 0;
23
+ exports.isIndexSet = exports.BitstringManager = exports.createStatusListManager = exports.StatusList2021Manager = exports.createDelegationVerifier = exports.DelegationCredentialVerifier = exports.createDelegationIssuer = exports.DelegationCredentialIssuer = exports.createDelegationErrorFormatter = exports.DelegationErrorFormatter = exports.OAuthRequiredError = exports.DelegationRequiredError = exports.NoOpToolProtectionCache = exports.InMemoryToolProtectionCache = exports.createProofVerificationError = exports.PROOF_VERIFICATION_ERROR_CODES = exports.ProofVerificationError = exports.migrateLegacyKeys = exports.StorageKeyHelpers = exports.createStorageProviders = exports.NoOpOAuthConfigCache = exports.InMemoryOAuthConfigCache = exports.BatchDelegationService = exports.OAuthTokenRetrievalService = exports.ProviderValidationError = exports.ProviderValidator = exports.CredentialAuthModeError = exports.ConsentOnlyModeError = exports.ProviderResolver = exports.OAuthProviderRegistry = exports.ToolContextBuilder = exports.OAuthService = exports.OAuthConfigService = exports.createSessionRegistrationService = exports.SessionRegistrationService = exports.authorizationMatches = exports.AccessControlApiService = exports.ProofVerifier = exports.CryptoService = exports.ToolProtectionService = exports.MCPIRuntimeBase = exports.MemoryIdentityProvider = exports.MemoryNonceCacheProvider = exports.MemoryStorageProvider = exports.IdentityProvider = exports.NonceCacheProvider = exports.StorageProvider = exports.FetchProvider = exports.ClockProvider = exports.CryptoProvider = void 0;
24
+ exports.IdpTokenResolver = exports.UserDidManager = exports.fetchRemoteConfig = exports.bytesToBase64 = exports.base64urlDecodeToString = exports.base64urlDecodeToBytes = exports.base64urlEncodeFromString = exports.base64urlEncodeFromBytes = exports.parseVCJWT = exports.completeVCJWT = exports.createUnsignedVCJWT = exports.canonicalizeJSON = exports.getSchemaStats = exports.getCriticalSchemas = exports.getSchemaById = exports.getSchemasByCategory = exports.getAllSchemas = exports.SCHEMA_REGISTRY = exports.createSchemaVerifier = exports.SchemaVerifier = exports.isValidBase58 = exports.base58Decode = exports.base58Encode = exports.resolveDidKeySync = exports.publicKeyToJwk = exports.extractPublicKeyFromDidKey = exports.isEd25519DidKey = exports.createDidKeyResolver = exports.MemoryDelegationGraphStorage = exports.MemoryStatusListStorage = exports.createCascadingRevocationManager = exports.CascadingRevocationManager = exports.createDelegationGraph = exports.DelegationGraphManager = void 0;
25
25
  // Base providers
26
26
  var base_1 = require("./providers/base");
27
27
  Object.defineProperty(exports, "CryptoProvider", { enumerable: true, get: function () { return base_1.CryptoProvider; } });
@@ -73,6 +73,7 @@ Object.defineProperty(exports, "OAuthProviderRegistry", { enumerable: true, get:
73
73
  var provider_resolver_1 = require("./services/provider-resolver");
74
74
  Object.defineProperty(exports, "ProviderResolver", { enumerable: true, get: function () { return provider_resolver_1.ProviderResolver; } });
75
75
  Object.defineProperty(exports, "ConsentOnlyModeError", { enumerable: true, get: function () { return provider_resolver_1.ConsentOnlyModeError; } });
76
+ Object.defineProperty(exports, "CredentialAuthModeError", { enumerable: true, get: function () { return provider_resolver_1.CredentialAuthModeError; } });
76
77
  // Provider Validator (Phase 3)
77
78
  var provider_validator_1 = require("./services/provider-validator");
78
79
  Object.defineProperty(exports, "ProviderValidator", { enumerable: true, get: function () { return provider_validator_1.ProviderValidator; } });
@@ -104,6 +105,10 @@ var tool_protection_1 = require("./types/tool-protection");
104
105
  Object.defineProperty(exports, "DelegationRequiredError", { enumerable: true, get: function () { return tool_protection_1.DelegationRequiredError; } });
105
106
  var oauth_required_error_1 = require("./types/oauth-required-error");
106
107
  Object.defineProperty(exports, "OAuthRequiredError", { enumerable: true, get: function () { return oauth_required_error_1.OAuthRequiredError; } });
108
+ // Delegation Error Formatter (client-specific messages)
109
+ var delegation_error_formatter_1 = require("./services/delegation-error-formatter");
110
+ Object.defineProperty(exports, "DelegationErrorFormatter", { enumerable: true, get: function () { return delegation_error_formatter_1.DelegationErrorFormatter; } });
111
+ Object.defineProperty(exports, "createDelegationErrorFormatter", { enumerable: true, get: function () { return delegation_error_formatter_1.createDelegationErrorFormatter; } });
107
112
  // Delegation (W3C VC-based)
108
113
  var vc_issuer_1 = require("./delegation/vc-issuer");
109
114
  Object.defineProperty(exports, "DelegationCredentialIssuer", { enumerable: true, get: function () { return vc_issuer_1.DelegationCredentialIssuer; } });
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Logging module exports
3
+ */
4
+ export { logger, createDefaultConsoleLogger, type Logger, type Level, } from "./logger";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ /**
3
+ * Logging module exports
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createDefaultConsoleLogger = exports.logger = void 0;
7
+ var logger_1 = require("./logger");
8
+ Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return logger_1.logger; } });
9
+ Object.defineProperty(exports, "createDefaultConsoleLogger", { enumerable: true, get: function () { return logger_1.createDefaultConsoleLogger; } });
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Transport-aware Logger for MCP-I
3
+ *
4
+ * Provides a lightweight, dependency-free logging interface that:
5
+ * - Maps log levels correctly for Cloudflare Workers (so wrangler tail shows correct severities)
6
+ * - Routes all logs to stderr for stdio transport (so stdout remains protocol-only)
7
+ * - Supports runtime configuration of log level and transport mode
8
+ */
9
+ export type Level = "debug" | "info" | "warn" | "error";
10
+ export interface Logger {
11
+ configure: (opts?: {
12
+ level?: Level;
13
+ transport?: string;
14
+ forceStderr?: boolean;
15
+ }) => void;
16
+ debug: (...args: any[]) => void;
17
+ info: (...args: any[]) => void;
18
+ warn: (...args: any[]) => void;
19
+ error: (...args: any[]) => void;
20
+ }
21
+ /**
22
+ * Create a default console logger with transport-aware behavior
23
+ *
24
+ * - Cloudflare Workers: Maps levels to console.debug/info/warn/error
25
+ * - stdio transport: Routes all levels to console.error (stderr) to keep stdout protocol-only
26
+ */
27
+ export declare function createDefaultConsoleLogger(): Logger;
28
+ /**
29
+ * Default singleton logger instance
30
+ * Configure via logger.configure() before use
31
+ */
32
+ export declare const logger: Logger;
33
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ /**
3
+ * Transport-aware Logger for MCP-I
4
+ *
5
+ * Provides a lightweight, dependency-free logging interface that:
6
+ * - Maps log levels correctly for Cloudflare Workers (so wrangler tail shows correct severities)
7
+ * - Routes all logs to stderr for stdio transport (so stdout remains protocol-only)
8
+ * - Supports runtime configuration of log level and transport mode
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.logger = void 0;
12
+ exports.createDefaultConsoleLogger = createDefaultConsoleLogger;
13
+ const SEVERITY = {
14
+ debug: 10,
15
+ info: 20,
16
+ warn: 30,
17
+ error: 40,
18
+ };
19
+ /**
20
+ * Create a default console logger with transport-aware behavior
21
+ *
22
+ * - Cloudflare Workers: Maps levels to console.debug/info/warn/error
23
+ * - stdio transport: Routes all levels to console.error (stderr) to keep stdout protocol-only
24
+ */
25
+ function createDefaultConsoleLogger() {
26
+ let level = "info";
27
+ let forceStderr = false;
28
+ function shouldLog(l) {
29
+ return SEVERITY[l] >= SEVERITY[level];
30
+ }
31
+ function write(l, ...args) {
32
+ if (!shouldLog(l))
33
+ return;
34
+ if (forceStderr) {
35
+ // stdio transport: all logs go to stderr (console.error)
36
+ // This ensures stdout remains protocol-only
37
+ console.error(...args);
38
+ return;
39
+ }
40
+ // Cloudflare Workers: map to appropriate console method
41
+ switch (l) {
42
+ case "debug":
43
+ if (typeof console.debug === "function") {
44
+ console.debug(...args);
45
+ }
46
+ else {
47
+ console.log(...args);
48
+ }
49
+ break;
50
+ case "info":
51
+ if (typeof console.info === "function") {
52
+ console.info(...args);
53
+ }
54
+ else {
55
+ console.log(...args);
56
+ }
57
+ break;
58
+ case "warn":
59
+ if (typeof console.warn === "function") {
60
+ console.warn(...args);
61
+ }
62
+ else {
63
+ console.error(...args);
64
+ }
65
+ break;
66
+ case "error":
67
+ console.error(...args);
68
+ break;
69
+ }
70
+ }
71
+ return {
72
+ configure(opts = {}) {
73
+ if (opts.level)
74
+ level = opts.level;
75
+ // Handle transport-based stderr routing
76
+ // - stdio transport: force all logs to stderr (stdout is protocol-only)
77
+ // - sse/http transports: use normal console routing
78
+ // - explicit forceStderr overrides transport-based behavior
79
+ if (opts.forceStderr === true) {
80
+ forceStderr = true;
81
+ }
82
+ else if (opts.forceStderr === false) {
83
+ forceStderr = false;
84
+ }
85
+ else if (opts.transport === "stdio") {
86
+ forceStderr = true;
87
+ }
88
+ else if (opts.transport === "sse" || opts.transport === "http") {
89
+ // Reset to normal console routing for non-stdio transports
90
+ forceStderr = false;
91
+ }
92
+ },
93
+ debug: (...a) => write("debug", ...a),
94
+ info: (...a) => write("info", ...a),
95
+ warn: (...a) => write("warn", ...a),
96
+ error: (...a) => write("error", ...a),
97
+ };
98
+ }
99
+ /**
100
+ * Default singleton logger instance
101
+ * Configure via logger.configure() before use
102
+ */
103
+ exports.logger = createDefaultConsoleLogger();
104
+ //# sourceMappingURL=logger.js.map
@@ -708,8 +708,8 @@ function authorizationMatches(delegationAuth, toolAuth) {
708
708
  return true;
709
709
  return delegationAuth.provider === toolAuth.provider;
710
710
  }
711
- // For credential, compare credentialType (undefined in toolAuth means "any type is acceptable")
712
- if (delegationAuth.type === "credential") {
711
+ // For verifiable_credential, compare credentialType
712
+ if (delegationAuth.type === "verifiable_credential") {
713
713
  // If tool doesn't specify a credential type, any type is acceptable
714
714
  if (!toolAuth.credentialType)
715
715
  return true;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * DelegationErrorFormatter - Formats delegation error messages for MCP clients
3
+ *
4
+ * This service provides a single source of truth for formatting delegation
5
+ * required error messages. It supports:
6
+ * - Default message templates
7
+ * - Client-specific message customization (claude, chatgpt, cursor, etc.)
8
+ * - Template interpolation with placeholders
9
+ * - Markdown support toggle per client
10
+ *
11
+ * @module @kya-os/mcp-i-core/services/delegation-error-formatter
12
+ */
13
+ import type { ClientMessageTemplate, ClientMessagesConfig } from "@kya-os/contracts/config";
14
+ export type { ClientMessageTemplate, ClientMessagesConfig };
15
+ /**
16
+ * Options for formatting a delegation error message
17
+ */
18
+ export interface DelegationErrorFormatOptions {
19
+ /** Name of the tool that requires delegation */
20
+ toolName: string;
21
+ /** URL where user can provide consent/delegation */
22
+ consentUrl?: string;
23
+ /** Scopes required for the tool */
24
+ scopes?: string[];
25
+ /** Client ID (e.g., "claude", "chatgpt", "cursor") - used for client-specific messages */
26
+ clientId?: string;
27
+ }
28
+ /**
29
+ * Options for formatting an OAuth error message
30
+ */
31
+ export interface OAuthErrorFormatOptions {
32
+ /** Name of the tool that requires OAuth */
33
+ toolName: string;
34
+ /** OAuth authorization URL */
35
+ oauthUrl?: string;
36
+ /** OAuth provider name (e.g., "GitHub", "Google") */
37
+ provider?: string;
38
+ /** Scopes required for the tool */
39
+ scopes?: string[];
40
+ /** Client ID (e.g., "claude", "chatgpt", "cursor") - used for client-specific messages */
41
+ clientId?: string;
42
+ }
43
+ /**
44
+ * Result of formatting a delegation error
45
+ */
46
+ export interface DelegationErrorResult {
47
+ /** Formatted message to display to the user */
48
+ message: string;
49
+ /** Consent URL (may be modified with extra params) */
50
+ consentUrl?: string;
51
+ }
52
+ /**
53
+ * Result of formatting an OAuth error
54
+ */
55
+ export interface OAuthErrorResult {
56
+ /** Formatted message to display to the user */
57
+ message: string;
58
+ /** OAuth URL (may be modified with extra params) */
59
+ oauthUrl?: string;
60
+ }
61
+ /**
62
+ * Service for formatting delegation error messages
63
+ *
64
+ * Provides consistent message formatting across different deployment patterns
65
+ * (agent, adapter) while supporting client-specific customization.
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * const formatter = new DelegationErrorFormatter();
70
+ * const { message } = formatter.format({
71
+ * toolName: "checkout",
72
+ * consentUrl: "https://example.com/consent",
73
+ * clientId: "claude"
74
+ * });
75
+ * ```
76
+ */
77
+ export declare class DelegationErrorFormatter {
78
+ private config?;
79
+ constructor(config?: ClientMessagesConfig);
80
+ /**
81
+ * Update the configuration
82
+ */
83
+ setConfig(config: ClientMessagesConfig): void;
84
+ /**
85
+ * Format a delegation error message
86
+ *
87
+ * @param options - Formatting options including toolName, consentUrl, and clientId
88
+ * @returns Formatted message and potentially modified consent URL
89
+ */
90
+ format(options: DelegationErrorFormatOptions): DelegationErrorResult;
91
+ /**
92
+ * Format an OAuth error message
93
+ *
94
+ * @param options - Formatting options including toolName, oauthUrl, provider, and clientId
95
+ * @returns Formatted message and potentially modified OAuth URL
96
+ */
97
+ formatOAuth(options: OAuthErrorFormatOptions): OAuthErrorResult;
98
+ /**
99
+ * Get the template for a specific client, merging with defaults
100
+ */
101
+ private getTemplate;
102
+ /**
103
+ * Build URL with extra parameters if configured
104
+ * Used for both consent URLs and OAuth URLs
105
+ */
106
+ private buildUrl;
107
+ /**
108
+ * Interpolate placeholders in a template string
109
+ *
110
+ * Uses a function replacement to avoid special pattern interpretation.
111
+ * JavaScript's String.replace() interprets patterns like $&, $', $` in the
112
+ * replacement string. Using () => value prevents this.
113
+ */
114
+ private interpolate;
115
+ /**
116
+ * Strip markdown links, converting [text](url) to plain "text: url"
117
+ */
118
+ private stripMarkdownLinks;
119
+ }
120
+ /**
121
+ * Create a delegation error formatter with optional configuration
122
+ */
123
+ export declare function createDelegationErrorFormatter(config?: ClientMessagesConfig): DelegationErrorFormatter;
124
+ //# sourceMappingURL=delegation-error-formatter.d.ts.map
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ /**
3
+ * DelegationErrorFormatter - Formats delegation error messages for MCP clients
4
+ *
5
+ * This service provides a single source of truth for formatting delegation
6
+ * required error messages. It supports:
7
+ * - Default message templates
8
+ * - Client-specific message customization (claude, chatgpt, cursor, etc.)
9
+ * - Template interpolation with placeholders
10
+ * - Markdown support toggle per client
11
+ *
12
+ * @module @kya-os/mcp-i-core/services/delegation-error-formatter
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.DelegationErrorFormatter = void 0;
16
+ exports.createDelegationErrorFormatter = createDelegationErrorFormatter;
17
+ /**
18
+ * Default message template (matches original adapter/agent behavior)
19
+ */
20
+ const DEFAULT_TEMPLATE = {
21
+ message: `Authorization required.
22
+
23
+ [Authorize {toolName}]({consentUrl})
24
+
25
+ Retry after authorizing.`,
26
+ noUrlMessage: `Authorization required for "{toolName}" but no consent URL is available.
27
+
28
+ Please contact the administrator to configure delegation for this tool.`,
29
+ oauthMessage: `Authorization required.
30
+
31
+ [Sign in with {provider}]({oauthUrl})
32
+
33
+ Retry after authorizing.`,
34
+ noOAuthUrlMessage: `Authorization required for "{toolName}" but no {provider} URL is available.
35
+
36
+ Please contact the administrator to configure OAuth for this tool.`,
37
+ supportsMarkdown: true,
38
+ };
39
+ /**
40
+ * Service for formatting delegation error messages
41
+ *
42
+ * Provides consistent message formatting across different deployment patterns
43
+ * (agent, adapter) while supporting client-specific customization.
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * const formatter = new DelegationErrorFormatter();
48
+ * const { message } = formatter.format({
49
+ * toolName: "checkout",
50
+ * consentUrl: "https://example.com/consent",
51
+ * clientId: "claude"
52
+ * });
53
+ * ```
54
+ */
55
+ class DelegationErrorFormatter {
56
+ config;
57
+ constructor(config) {
58
+ this.config = config;
59
+ }
60
+ /**
61
+ * Update the configuration
62
+ */
63
+ setConfig(config) {
64
+ this.config = config;
65
+ }
66
+ /**
67
+ * Format a delegation error message
68
+ *
69
+ * @param options - Formatting options including toolName, consentUrl, and clientId
70
+ * @returns Formatted message and potentially modified consent URL
71
+ */
72
+ format(options) {
73
+ const { toolName, consentUrl, scopes, clientId } = options;
74
+ // Get the appropriate template for this client
75
+ const template = this.getTemplate(clientId);
76
+ // Build the final consent URL with any extra params
77
+ const finalUrl = this.buildUrl(consentUrl, template);
78
+ // Choose message based on whether we have a consent URL
79
+ let message;
80
+ if (finalUrl) {
81
+ const messageTemplate = template.message ?? DEFAULT_TEMPLATE.message;
82
+ message = this.interpolate(messageTemplate, {
83
+ toolName,
84
+ consentUrl: finalUrl,
85
+ scopes: scopes?.join(", ") ?? "",
86
+ });
87
+ // If client doesn't support markdown, convert markdown links to plain text
88
+ if (template.supportsMarkdown === false) {
89
+ message = this.stripMarkdownLinks(message);
90
+ }
91
+ }
92
+ else {
93
+ const noUrlTemplate = template.noUrlMessage ?? DEFAULT_TEMPLATE.noUrlMessage;
94
+ message = this.interpolate(noUrlTemplate, {
95
+ toolName,
96
+ consentUrl: "",
97
+ scopes: scopes?.join(", ") ?? "",
98
+ });
99
+ }
100
+ return { message, consentUrl: finalUrl };
101
+ }
102
+ /**
103
+ * Format an OAuth error message
104
+ *
105
+ * @param options - Formatting options including toolName, oauthUrl, provider, and clientId
106
+ * @returns Formatted message and potentially modified OAuth URL
107
+ */
108
+ formatOAuth(options) {
109
+ const { toolName, oauthUrl, provider = "OAuth", scopes, clientId } = options;
110
+ // Get the appropriate template for this client
111
+ const template = this.getTemplate(clientId);
112
+ // Build the final OAuth URL with any extra params
113
+ const finalUrl = this.buildUrl(oauthUrl, template);
114
+ // Choose message based on whether we have an OAuth URL
115
+ let message;
116
+ if (finalUrl) {
117
+ const messageTemplate = template.oauthMessage ?? DEFAULT_TEMPLATE.oauthMessage;
118
+ message = this.interpolate(messageTemplate, {
119
+ toolName,
120
+ oauthUrl: finalUrl,
121
+ provider,
122
+ scopes: scopes?.join(", ") ?? "",
123
+ });
124
+ // If client doesn't support markdown, convert markdown links to plain text
125
+ if (template.supportsMarkdown === false) {
126
+ message = this.stripMarkdownLinks(message);
127
+ }
128
+ }
129
+ else {
130
+ const noUrlTemplate = template.noOAuthUrlMessage ?? DEFAULT_TEMPLATE.noOAuthUrlMessage;
131
+ message = this.interpolate(noUrlTemplate, {
132
+ toolName,
133
+ oauthUrl: "",
134
+ provider,
135
+ scopes: scopes?.join(", ") ?? "",
136
+ });
137
+ }
138
+ return { message, oauthUrl: finalUrl };
139
+ }
140
+ /**
141
+ * Get the template for a specific client, merging with defaults
142
+ */
143
+ getTemplate(clientId) {
144
+ const defaultTemplate = this.config?.default ?? {};
145
+ // If no client ID or no client-specific config, use default
146
+ if (!clientId || !this.config?.clients?.[clientId]) {
147
+ return {
148
+ ...DEFAULT_TEMPLATE,
149
+ ...defaultTemplate,
150
+ };
151
+ }
152
+ // Merge: DEFAULT_TEMPLATE < config.default < config.clients[clientId]
153
+ return {
154
+ ...DEFAULT_TEMPLATE,
155
+ ...defaultTemplate,
156
+ ...this.config.clients[clientId],
157
+ };
158
+ }
159
+ /**
160
+ * Build URL with extra parameters if configured
161
+ * Used for both consent URLs and OAuth URLs
162
+ */
163
+ buildUrl(baseUrl, template) {
164
+ if (!baseUrl)
165
+ return undefined;
166
+ // If no extra params, return as-is
167
+ if (!template.extraParams || Object.keys(template.extraParams).length === 0) {
168
+ return baseUrl;
169
+ }
170
+ // Add extra params to URL
171
+ try {
172
+ const url = new URL(baseUrl);
173
+ for (const [key, value] of Object.entries(template.extraParams)) {
174
+ url.searchParams.set(key, value);
175
+ }
176
+ return url.toString();
177
+ }
178
+ catch {
179
+ // If URL parsing fails, return original
180
+ return baseUrl;
181
+ }
182
+ }
183
+ /**
184
+ * Interpolate placeholders in a template string
185
+ *
186
+ * Uses a function replacement to avoid special pattern interpretation.
187
+ * JavaScript's String.replace() interprets patterns like $&, $', $` in the
188
+ * replacement string. Using () => value prevents this.
189
+ */
190
+ interpolate(template, values) {
191
+ let result = template;
192
+ for (const [key, value] of Object.entries(values)) {
193
+ // Use function replacement to prevent special pattern interpretation
194
+ // e.g., URLs containing $& would otherwise get corrupted
195
+ result = result.replace(new RegExp(`\\{${key}\\}`, "g"), () => value);
196
+ }
197
+ return result;
198
+ }
199
+ /**
200
+ * Strip markdown links, converting [text](url) to plain "text: url"
201
+ */
202
+ stripMarkdownLinks(text) {
203
+ // Match [link text](url) and convert to "link text: url"
204
+ return text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, "$1: $2");
205
+ }
206
+ }
207
+ exports.DelegationErrorFormatter = DelegationErrorFormatter;
208
+ /**
209
+ * Create a delegation error formatter with optional configuration
210
+ */
211
+ function createDelegationErrorFormatter(config) {
212
+ return new DelegationErrorFormatter(config);
213
+ }
214
+ //# sourceMappingURL=delegation-error-formatter.js.map
@@ -4,4 +4,6 @@ export { AccessControlApiService, authorizationMatches, } from './access-control
4
4
  export type { AccessControlApiServiceConfig, AccessControlApiServiceMetrics, } from './access-control.service.js';
5
5
  export { SessionRegistrationService, createSessionRegistrationService, } from './session-registration.service.js';
6
6
  export type { SessionRegistrationServiceConfig, SessionRegistrationResult, } from './session-registration.service.js';
7
+ export { DelegationErrorFormatter, createDelegationErrorFormatter, } from './delegation-error-formatter.js';
8
+ export type { DelegationErrorFormatOptions, DelegationErrorResult, OAuthErrorFormatOptions, OAuthErrorResult, ClientMessageTemplate, ClientMessagesConfig, } from './delegation-error-formatter.js';
7
9
  //# sourceMappingURL=index.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createSessionRegistrationService = exports.SessionRegistrationService = exports.authorizationMatches = exports.AccessControlApiService = exports.CryptoService = void 0;
3
+ exports.createDelegationErrorFormatter = exports.DelegationErrorFormatter = exports.createSessionRegistrationService = exports.SessionRegistrationService = exports.authorizationMatches = exports.AccessControlApiService = exports.CryptoService = void 0;
4
4
  var crypto_service_js_1 = require("./crypto.service.js");
5
5
  Object.defineProperty(exports, "CryptoService", { enumerable: true, get: function () { return crypto_service_js_1.CryptoService; } });
6
6
  var access_control_service_js_1 = require("./access-control.service.js");
@@ -9,4 +9,7 @@ Object.defineProperty(exports, "authorizationMatches", { enumerable: true, get:
9
9
  var session_registration_service_js_1 = require("./session-registration.service.js");
10
10
  Object.defineProperty(exports, "SessionRegistrationService", { enumerable: true, get: function () { return session_registration_service_js_1.SessionRegistrationService; } });
11
11
  Object.defineProperty(exports, "createSessionRegistrationService", { enumerable: true, get: function () { return session_registration_service_js_1.createSessionRegistrationService; } });
12
+ var delegation_error_formatter_js_1 = require("./delegation-error-formatter.js");
13
+ Object.defineProperty(exports, "DelegationErrorFormatter", { enumerable: true, get: function () { return delegation_error_formatter_js_1.DelegationErrorFormatter; } });
14
+ Object.defineProperty(exports, "createDelegationErrorFormatter", { enumerable: true, get: function () { return delegation_error_formatter_js_1.createDelegationErrorFormatter; } });
12
15
  //# sourceMappingURL=index.js.map
@@ -17,6 +17,17 @@ export declare class ConsentOnlyModeError extends Error {
17
17
  readonly toolProtection: ToolProtection;
18
18
  constructor(toolProtection: ToolProtection);
19
19
  }
20
+ /**
21
+ * Error thrown when a tool requires credential/password-based authentication
22
+ * This is NOT an error condition - it's a signal to use credential auth flow
23
+ * (username/password, email/password, etc.) instead of OAuth
24
+ */
25
+ export declare class CredentialAuthModeError extends Error {
26
+ readonly toolProtection: ToolProtection;
27
+ /** The credential provider ID configured for this tool */
28
+ readonly provider: string;
29
+ constructor(toolProtection: ToolProtection, provider: string);
30
+ }
20
31
  /**
21
32
  * Resolves OAuth provider for tools with priority-based fallback strategy
22
33
  *
@@ -39,6 +50,17 @@ export declare class ProviderResolver {
39
50
  * @returns true if consent-only mode
40
51
  */
41
52
  isConsentOnlyMode(toolProtection: ToolProtection): boolean;
53
+ /**
54
+ * Check if a tool is configured for credential/password-based authentication
55
+ * This includes username/password, email/password, etc.
56
+ *
57
+ * @param toolProtection - Tool protection configuration
58
+ * @returns Object with isCredential flag and optional provider ID
59
+ */
60
+ isCredentialAuthMode(toolProtection: ToolProtection): {
61
+ isCredential: boolean;
62
+ provider?: string;
63
+ };
42
64
  /**
43
65
  * Resolve OAuth provider for a tool
44
66
  *
@@ -46,6 +68,7 @@ export declare class ProviderResolver {
46
68
  * @param projectId - Project ID for fetching provider config
47
69
  * @returns Provider name (never null - throws if cannot resolve)
48
70
  * @throws ConsentOnlyModeError if tool is consent-only (not a real error)
71
+ * @throws CredentialAuthModeError if tool requires password/credential auth
49
72
  * @throws Error if provider cannot be resolved
50
73
  */
51
74
  resolveProvider(toolProtection: ToolProtection, projectId: string): Promise<string>;
@@ -8,7 +8,7 @@
8
8
  * @package @kya-os/mcp-i-core
9
9
  */
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.ProviderResolver = exports.ConsentOnlyModeError = void 0;
11
+ exports.ProviderResolver = exports.CredentialAuthModeError = exports.ConsentOnlyModeError = void 0;
12
12
  /**
13
13
  * Error thrown when a tool is configured for consent-only mode (no OAuth needed)
14
14
  * This is NOT an error condition - it's a signal to skip OAuth flow
@@ -22,6 +22,23 @@ class ConsentOnlyModeError extends Error {
22
22
  }
23
23
  }
24
24
  exports.ConsentOnlyModeError = ConsentOnlyModeError;
25
+ /**
26
+ * Error thrown when a tool requires credential/password-based authentication
27
+ * This is NOT an error condition - it's a signal to use credential auth flow
28
+ * (username/password, email/password, etc.) instead of OAuth
29
+ */
30
+ class CredentialAuthModeError extends Error {
31
+ toolProtection;
32
+ /** The credential provider ID configured for this tool */
33
+ provider;
34
+ constructor(toolProtection, provider) {
35
+ super(`Tool requires credential authentication with provider "${provider}"`);
36
+ this.toolProtection = toolProtection;
37
+ this.name = "CredentialAuthModeError";
38
+ this.provider = provider;
39
+ }
40
+ }
41
+ exports.CredentialAuthModeError = CredentialAuthModeError;
25
42
  /**
26
43
  * Resolves OAuth provider for tools with priority-based fallback strategy
27
44
  *
@@ -53,6 +70,23 @@ class ProviderResolver {
53
70
  }
54
71
  return false;
55
72
  }
73
+ /**
74
+ * Check if a tool is configured for credential/password-based authentication
75
+ * This includes username/password, email/password, etc.
76
+ *
77
+ * @param toolProtection - Tool protection configuration
78
+ * @returns Object with isCredential flag and optional provider ID
79
+ */
80
+ isCredentialAuthMode(toolProtection) {
81
+ // Check explicit authorization.type === 'password'
82
+ if (toolProtection.authorization?.type === "password") {
83
+ return {
84
+ isCredential: true,
85
+ provider: toolProtection.authorization.provider || "credentials",
86
+ };
87
+ }
88
+ return { isCredential: false };
89
+ }
56
90
  /**
57
91
  * Resolve OAuth provider for a tool
58
92
  *
@@ -60,14 +94,21 @@ class ProviderResolver {
60
94
  * @param projectId - Project ID for fetching provider config
61
95
  * @returns Provider name (never null - throws if cannot resolve)
62
96
  * @throws ConsentOnlyModeError if tool is consent-only (not a real error)
97
+ * @throws CredentialAuthModeError if tool requires password/credential auth
63
98
  * @throws Error if provider cannot be resolved
64
99
  */
65
100
  async resolveProvider(toolProtection, projectId) {
66
- // Priority 0: Check for consent-only mode (no OAuth required)
101
+ // Priority 0a: Check for consent-only mode (no OAuth required)
67
102
  if (this.isConsentOnlyMode(toolProtection)) {
68
103
  console.error(`[ProviderResolver] Tool is consent-only mode (authorization.type=none), skipping OAuth resolution`);
69
104
  throw new ConsentOnlyModeError(toolProtection);
70
105
  }
106
+ // Priority 0b: Check for credential/password auth mode (not OAuth)
107
+ const credentialCheck = this.isCredentialAuthMode(toolProtection);
108
+ if (credentialCheck.isCredential) {
109
+ console.error(`[ProviderResolver] Tool requires credential auth (authorization.type=password), provider="${credentialCheck.provider}"`);
110
+ throw new CredentialAuthModeError(toolProtection, credentialCheck.provider);
111
+ }
71
112
  // Priority 1: Tool-specific provider (Phase 2+ preferred)
72
113
  if (toolProtection.oauthProvider) {
73
114
  // Ensure registry is loaded before checking
@@ -13,6 +13,7 @@
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
14
  exports.ToolContextBuilder = void 0;
15
15
  const oauth_required_error_js_1 = require("../types/oauth-required-error.js");
16
+ const provider_resolver_js_1 = require("./provider-resolver.js");
16
17
  /**
17
18
  * Builder for tool execution context
18
19
  *
@@ -53,7 +54,18 @@ class ToolContextBuilder {
53
54
  provider = await this.resolveProvider(toolProtection);
54
55
  }
55
56
  catch (error) {
56
- // Provider resolution failed - cannot build context
57
+ // ConsentOnlyModeError and CredentialAuthModeError are NOT errors
58
+ // They're signals about what auth flow to use - re-throw for caller to handle
59
+ if (error instanceof provider_resolver_js_1.ConsentOnlyModeError ||
60
+ error instanceof provider_resolver_js_1.CredentialAuthModeError) {
61
+ this.config.logger("[ToolContextBuilder] Special auth mode detected, re-throwing", {
62
+ toolName,
63
+ errorType: error.name,
64
+ message: error.message,
65
+ });
66
+ throw error;
67
+ }
68
+ // Other provider resolution errors - cannot build context
57
69
  this.config.logger("[ToolContextBuilder] Provider not resolved", {
58
70
  toolName,
59
71
  userDid: userDid.substring(0, 20) + "...",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kya-os/mcp-i-core",
3
- "version": "1.4.0",
3
+ "version": "1.4.3",
4
4
  "description": "Core runtime and types for MCP-I framework",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -28,7 +28,7 @@
28
28
  "prepublishOnly": "npm run build && node ../create-mcpi-app/scripts/validate-no-workspace.js"
29
29
  },
30
30
  "dependencies": {
31
- "@kya-os/contracts": "^1.7.0",
31
+ "@kya-os/contracts": "^1.7.6",
32
32
  "jose": "^5.6.3",
33
33
  "json-canonicalize": "^2.0.0",
34
34
  "zod": "^3.25.76"