@mcp-z/oauth 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +71 -0
  3. package/dist/cjs/account-utils.d.cts +107 -0
  4. package/dist/cjs/account-utils.d.ts +107 -0
  5. package/dist/cjs/account-utils.js +481 -0
  6. package/dist/cjs/account-utils.js.map +1 -0
  7. package/dist/cjs/index.d.cts +19 -0
  8. package/dist/cjs/index.d.ts +19 -0
  9. package/dist/cjs/index.js +149 -0
  10. package/dist/cjs/index.js.map +1 -0
  11. package/dist/cjs/jwt-auth.d.cts +53 -0
  12. package/dist/cjs/jwt-auth.d.ts +53 -0
  13. package/dist/cjs/jwt-auth.js +417 -0
  14. package/dist/cjs/jwt-auth.js.map +1 -0
  15. package/dist/cjs/key-utils.d.cts +131 -0
  16. package/dist/cjs/key-utils.d.ts +131 -0
  17. package/dist/cjs/key-utils.js +421 -0
  18. package/dist/cjs/key-utils.js.map +1 -0
  19. package/dist/cjs/lib/account-server/index.d.cts +45 -0
  20. package/dist/cjs/lib/account-server/index.d.ts +45 -0
  21. package/dist/cjs/lib/account-server/index.js +67 -0
  22. package/dist/cjs/lib/account-server/index.js.map +1 -0
  23. package/dist/cjs/lib/account-server/loopback.d.cts +22 -0
  24. package/dist/cjs/lib/account-server/loopback.d.ts +22 -0
  25. package/dist/cjs/lib/account-server/loopback.js +778 -0
  26. package/dist/cjs/lib/account-server/loopback.js.map +1 -0
  27. package/dist/cjs/lib/account-server/me.d.cts +23 -0
  28. package/dist/cjs/lib/account-server/me.d.ts +23 -0
  29. package/dist/cjs/lib/account-server/me.js +412 -0
  30. package/dist/cjs/lib/account-server/me.js.map +1 -0
  31. package/dist/cjs/lib/account-server/shared-utils.d.cts +6 -0
  32. package/dist/cjs/lib/account-server/shared-utils.d.ts +6 -0
  33. package/dist/cjs/lib/account-server/shared-utils.js +235 -0
  34. package/dist/cjs/lib/account-server/shared-utils.js.map +1 -0
  35. package/dist/cjs/lib/account-server/stateless.d.cts +20 -0
  36. package/dist/cjs/lib/account-server/stateless.d.ts +20 -0
  37. package/dist/cjs/lib/account-server/stateless.js +32 -0
  38. package/dist/cjs/lib/account-server/stateless.js.map +1 -0
  39. package/dist/cjs/lib/account-server/types.d.cts +32 -0
  40. package/dist/cjs/lib/account-server/types.d.ts +32 -0
  41. package/dist/cjs/lib/account-server/types.js +7 -0
  42. package/dist/cjs/lib/account-server/types.js.map +1 -0
  43. package/dist/cjs/lib/dcr-types.d.cts +126 -0
  44. package/dist/cjs/lib/dcr-types.d.ts +126 -0
  45. package/dist/cjs/lib/dcr-types.js +12 -0
  46. package/dist/cjs/lib/dcr-types.js.map +1 -0
  47. package/dist/cjs/lib/rfc-metadata-types.d.cts +46 -0
  48. package/dist/cjs/lib/rfc-metadata-types.d.ts +46 -0
  49. package/dist/cjs/lib/rfc-metadata-types.js +8 -0
  50. package/dist/cjs/lib/rfc-metadata-types.js.map +1 -0
  51. package/dist/cjs/package.json +1 -0
  52. package/dist/cjs/pkce.d.cts +36 -0
  53. package/dist/cjs/pkce.d.ts +36 -0
  54. package/dist/cjs/pkce.js +25 -0
  55. package/dist/cjs/pkce.js.map +1 -0
  56. package/dist/cjs/sanitizer.d.cts +37 -0
  57. package/dist/cjs/sanitizer.d.ts +37 -0
  58. package/dist/cjs/sanitizer.js +407 -0
  59. package/dist/cjs/sanitizer.js.map +1 -0
  60. package/dist/cjs/schemas/index.d.cts +36 -0
  61. package/dist/cjs/schemas/index.d.ts +36 -0
  62. package/dist/cjs/schemas/index.js +28 -0
  63. package/dist/cjs/schemas/index.js.map +1 -0
  64. package/dist/cjs/session-auth.d.cts +79 -0
  65. package/dist/cjs/session-auth.d.ts +79 -0
  66. package/dist/cjs/session-auth.js +354 -0
  67. package/dist/cjs/session-auth.js.map +1 -0
  68. package/dist/cjs/templates.d.cts +18 -0
  69. package/dist/cjs/templates.d.ts +18 -0
  70. package/dist/cjs/templates.js +38 -0
  71. package/dist/cjs/templates.js.map +1 -0
  72. package/dist/cjs/types.d.cts +343 -0
  73. package/dist/cjs/types.d.ts +343 -0
  74. package/dist/cjs/types.js +210 -0
  75. package/dist/cjs/types.js.map +1 -0
  76. package/dist/esm/account-utils.d.ts +107 -0
  77. package/dist/esm/account-utils.js +179 -0
  78. package/dist/esm/account-utils.js.map +1 -0
  79. package/dist/esm/index.d.ts +19 -0
  80. package/dist/esm/index.js +23 -0
  81. package/dist/esm/index.js.map +1 -0
  82. package/dist/esm/jwt-auth.d.ts +53 -0
  83. package/dist/esm/jwt-auth.js +164 -0
  84. package/dist/esm/jwt-auth.js.map +1 -0
  85. package/dist/esm/key-utils.d.ts +131 -0
  86. package/dist/esm/key-utils.js +143 -0
  87. package/dist/esm/key-utils.js.map +1 -0
  88. package/dist/esm/lib/account-server/index.d.ts +45 -0
  89. package/dist/esm/lib/account-server/index.js +41 -0
  90. package/dist/esm/lib/account-server/index.js.map +1 -0
  91. package/dist/esm/lib/account-server/loopback.d.ts +22 -0
  92. package/dist/esm/lib/account-server/loopback.js +372 -0
  93. package/dist/esm/lib/account-server/loopback.js.map +1 -0
  94. package/dist/esm/lib/account-server/me.d.ts +23 -0
  95. package/dist/esm/lib/account-server/me.js +170 -0
  96. package/dist/esm/lib/account-server/me.js.map +1 -0
  97. package/dist/esm/lib/account-server/shared-utils.d.ts +6 -0
  98. package/dist/esm/lib/account-server/shared-utils.js +24 -0
  99. package/dist/esm/lib/account-server/shared-utils.js.map +1 -0
  100. package/dist/esm/lib/account-server/stateless.d.ts +20 -0
  101. package/dist/esm/lib/account-server/stateless.js +25 -0
  102. package/dist/esm/lib/account-server/stateless.js.map +1 -0
  103. package/dist/esm/lib/account-server/types.d.ts +32 -0
  104. package/dist/esm/lib/account-server/types.js +6 -0
  105. package/dist/esm/lib/account-server/types.js.map +1 -0
  106. package/dist/esm/lib/dcr-types.d.ts +126 -0
  107. package/dist/esm/lib/dcr-types.js +13 -0
  108. package/dist/esm/lib/dcr-types.js.map +1 -0
  109. package/dist/esm/lib/rfc-metadata-types.d.ts +46 -0
  110. package/dist/esm/lib/rfc-metadata-types.js +7 -0
  111. package/dist/esm/lib/rfc-metadata-types.js.map +1 -0
  112. package/dist/esm/package.json +1 -0
  113. package/dist/esm/pkce.d.ts +36 -0
  114. package/dist/esm/pkce.js +33 -0
  115. package/dist/esm/pkce.js.map +1 -0
  116. package/dist/esm/sanitizer.d.ts +37 -0
  117. package/dist/esm/sanitizer.js +256 -0
  118. package/dist/esm/sanitizer.js.map +1 -0
  119. package/dist/esm/schemas/index.d.ts +36 -0
  120. package/dist/esm/schemas/index.js +19 -0
  121. package/dist/esm/schemas/index.js.map +1 -0
  122. package/dist/esm/session-auth.d.ts +79 -0
  123. package/dist/esm/session-auth.js +141 -0
  124. package/dist/esm/session-auth.js.map +1 -0
  125. package/dist/esm/templates.d.ts +18 -0
  126. package/dist/esm/templates.js +132 -0
  127. package/dist/esm/templates.js.map +1 -0
  128. package/dist/esm/types.d.ts +343 -0
  129. package/dist/esm/types.js +34 -0
  130. package/dist/esm/types.js.map +1 -0
  131. package/package.json +82 -0
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Type definitions for multi-account management and OAuth integration
3
+ */
4
+ import type { AnySchema, ZodRawShapeCompat } from '@modelcontextprotocol/sdk/server/zod-compat.js';
5
+ import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
6
+ import type { CallToolResult, GetPromptResult, ServerNotification, ServerRequest, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
7
+ export type Logger = Pick<Console, 'info' | 'error' | 'warn' | 'debug'>;
8
+ export interface AccountInfo {
9
+ email: string;
10
+ alias?: string;
11
+ addedAt: string;
12
+ lastUsed?: string;
13
+ metadata?: {
14
+ name?: string;
15
+ picture?: string;
16
+ [key: string]: unknown;
17
+ };
18
+ }
19
+ /**
20
+ * MCP tool module definition with configuration and handler function.
21
+ *
22
+ * Represents a registered tool in the Model Context Protocol server that can be
23
+ * invoked by MCP clients. Tools are the primary mechanism for executing operations
24
+ * in response to client requests.
25
+ *
26
+ * @property name - Unique tool identifier (e.g., "gmail-message-send", "sheets-values-get")
27
+ * @property config - Tool configuration including description and schemas
28
+ * @property config.description - Human-readable description shown to MCP clients
29
+ * @property config.inputSchema - Zod schema defining tool arguments (JSON-serializable)
30
+ * @property config.outputSchema - Zod schema defining tool response structure
31
+ * @property handler - Async function that executes the tool operation
32
+ *
33
+ * @remarks
34
+ * This is the runtime representation of an MCP tool after registration. The handler
35
+ * receives JSON-serializable arguments validated against inputSchema and returns
36
+ * a CallToolResult validated against outputSchema.
37
+ *
38
+ * Tools are typically created using tool factory functions and registered with the
39
+ * MCP server during initialization.
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * const tool: McpTool = {
44
+ * name: "gmail-message-send",
45
+ * config: {
46
+ * description: "Send an email message",
47
+ * inputSchema: { to: { type: "string" }, subject: { type: "string" } },
48
+ * outputSchema: { result: { type: "object" } }
49
+ * },
50
+ * handler: async (args, context) => {
51
+ * // Implementation
52
+ * return { content: [{ type: "text", text: "Message sent" }] };
53
+ * }
54
+ * };
55
+ * ```
56
+ *
57
+ * @see {@link McpPrompt} for prompt module definition
58
+ */
59
+ export interface McpTool {
60
+ name: string;
61
+ config: {
62
+ description: string;
63
+ inputSchema: Record<string, unknown>;
64
+ outputSchema: Record<string, unknown>;
65
+ };
66
+ handler: (args: unknown, context?: unknown) => Promise<CallToolResult>;
67
+ }
68
+ /**
69
+ * MCP prompt module definition with configuration and handler function.
70
+ *
71
+ * Represents a registered prompt template in the Model Context Protocol server that
72
+ * can be retrieved and rendered by MCP clients. Prompts provide reusable templates
73
+ * for common interaction patterns.
74
+ *
75
+ * @property name - Unique prompt identifier (e.g., "draft-email", "summarize-thread")
76
+ * @property config - Prompt configuration (schema and metadata are prompt-specific)
77
+ * @property handler - Async function that generates the prompt content
78
+ *
79
+ * @remarks
80
+ * This is the runtime representation of an MCP prompt after registration. Unlike
81
+ * {@link McpTool} which executes operations, prompts generate templated content
82
+ * that clients can use to structure interactions.
83
+ *
84
+ * The handler receives optional arguments and returns a GetPromptResult containing
85
+ * the rendered prompt messages.
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * const prompt: McpPrompt = {
90
+ * name: "draft-email",
91
+ * config: {
92
+ * description: "Generate email draft from key points",
93
+ * arguments: [{ name: "points", description: "Key points to include" }]
94
+ * },
95
+ * handler: async (args) => {
96
+ * const points = args?.points || [];
97
+ * return {
98
+ * messages: [{
99
+ * role: "user",
100
+ * content: { type: "text", text: `Draft email covering: ${points.join(", ")}` }
101
+ * }]
102
+ * };
103
+ * }
104
+ * };
105
+ * ```
106
+ *
107
+ * @see {@link McpTool} for tool module definition
108
+ */
109
+ export interface McpPrompt {
110
+ name: string;
111
+ config: unknown;
112
+ handler: (args: unknown) => Promise<GetPromptResult>;
113
+ }
114
+ export declare class AccountManagerError extends Error {
115
+ code: string;
116
+ retryable: boolean;
117
+ constructor(message: string, code: string, retryable?: boolean);
118
+ }
119
+ export declare class AccountNotFoundError extends AccountManagerError {
120
+ constructor(accountRef: string);
121
+ }
122
+ export declare class ConfigurationError extends AccountManagerError {
123
+ constructor(message: string);
124
+ }
125
+ export declare class RequiresAuthenticationError extends AccountManagerError {
126
+ accountId: string | undefined;
127
+ constructor(service: string, accountId?: string);
128
+ }
129
+ export interface AuthEmailProvider {
130
+ getUserEmail(accountId?: string): Promise<string>;
131
+ authenticateNewAccount?(): Promise<string>;
132
+ }
133
+ export interface UserAuthProvider {
134
+ getUserId(req: unknown): Promise<string>;
135
+ }
136
+ export interface JWTUserAuthConfig {
137
+ secret?: string;
138
+ publicKey?: string | object;
139
+ jwksUrl?: string;
140
+ issuer?: string | string[];
141
+ audience?: string | string[];
142
+ userIdClaim?: string;
143
+ algorithms?: string[];
144
+ clockTolerance?: number;
145
+ }
146
+ export interface SessionUserAuthConfig {
147
+ sessionSecret: string;
148
+ cookieName?: string;
149
+ algorithm?: 'sha256' | 'sha512';
150
+ }
151
+ export interface Credentials {
152
+ accessToken: string;
153
+ expiresAt?: number;
154
+ refreshToken?: string;
155
+ scope?: string;
156
+ tokenType?: string;
157
+ idToken?: string;
158
+ }
159
+ export type AuthFlowDescriptor = {
160
+ kind: 'credentials';
161
+ connection?: string;
162
+ provider?: string;
163
+ credentials: Credentials;
164
+ } | {
165
+ kind: 'auth_url';
166
+ connection?: string;
167
+ provider?: string;
168
+ url: string;
169
+ txn?: string;
170
+ state?: string;
171
+ codeVerifier?: string;
172
+ poll?: {
173
+ statusUrl: string;
174
+ interval?: number;
175
+ };
176
+ hint?: string;
177
+ } | {
178
+ kind: 'device_code';
179
+ connection?: string;
180
+ provider?: string;
181
+ txn?: string;
182
+ device: {
183
+ userCode: string;
184
+ verificationUri: string;
185
+ verificationUriComplete?: string;
186
+ expiresIn: number;
187
+ interval: number;
188
+ };
189
+ poll?: {
190
+ statusUrl: string;
191
+ interval?: number;
192
+ };
193
+ hint?: string;
194
+ } | {
195
+ kind: 'error';
196
+ error: string;
197
+ code?: number;
198
+ };
199
+ export declare class AuthRequiredError extends Error {
200
+ descriptor: AuthFlowDescriptor;
201
+ constructor(descriptor: AuthFlowDescriptor, message?: string);
202
+ }
203
+ export interface CachedToken {
204
+ accessToken: string;
205
+ refreshToken?: string;
206
+ expiresAt?: number;
207
+ scope?: string;
208
+ }
209
+ /**
210
+ * Tool config signature - explicit structural type mirroring SDK registerTool config
211
+ *
212
+ * Uses explicit structure instead of Parameters<> extraction to avoid TypeScript inference
213
+ * collapse to 'never' when using ToolModule[] arrays. The deep conditional types from
214
+ * Parameters<> cannot be unified across array elements.
215
+ *
216
+ * Validated against SDK signature for compatibility - compile errors if SDK changes.
217
+ *
218
+ * NOTE: This type is duplicated in @mcp-z/server for architectural independence.
219
+ * Keep these definitions synchronized manually when updating.
220
+ */
221
+ export type ToolConfig = {
222
+ title?: string;
223
+ description?: string;
224
+ inputSchema?: ZodRawShapeCompat | AnySchema;
225
+ outputSchema?: ZodRawShapeCompat | AnySchema;
226
+ annotations?: ToolAnnotations;
227
+ _meta?: Record<string, unknown>;
228
+ };
229
+ /**
230
+ * Tool handler signature with generic support for middleware.
231
+ *
232
+ * @template TArgs - Tool arguments type (default: unknown for SDK compatibility)
233
+ * @template TExtra - Request handler extra type (default: RequestHandlerExtra from SDK)
234
+ *
235
+ * Defaults provide SDK-extracted types for compatibility with MCP SDK.
236
+ * Generic parameters enable type-safe middleware transformation.
237
+ *
238
+ * NOTE: This interface is duplicated in @mcp-z/server for architectural independence.
239
+ * Keep these definitions synchronized manually when updating.
240
+ */
241
+ export type ToolHandler<TArgs = unknown, TExtra = RequestHandlerExtra<ServerRequest, ServerNotification>> = (args: TArgs, extra: TExtra) => Promise<CallToolResult>;
242
+ /**
243
+ * Tool module interface with bounded generics.
244
+ *
245
+ * @template TConfig - Tool config type (default: SDK ToolConfig)
246
+ * @template THandler - Handler function type (default: SDK ToolHandler)
247
+ *
248
+ * Use without generics for SDK-typed tools:
249
+ * - Business tool factories: `ToolModule`
250
+ * - Tool registration: `ToolModule[]`
251
+ *
252
+ * Use with generics for middleware transformation:
253
+ * - Auth middleware: `ToolModule<ToolConfig, ToolHandler<TArgs, EnrichedExtra>>`
254
+ *
255
+ * The bounds ensure compatibility with SDK registration.
256
+ *
257
+ * NOTE: This interface is duplicated in @mcp-z/server for architectural independence.
258
+ * Keep these definitions synchronized manually when updating.
259
+ *
260
+ * @see {@link ToolHandler} for handler function signature
261
+ * @see {@link AuthMiddlewareWrapper} for middleware wrapper pattern
262
+ */
263
+ export interface ToolModule<TConfig = ToolConfig, THandler = unknown> {
264
+ name: string;
265
+ config: TConfig;
266
+ handler: THandler;
267
+ }
268
+ /**
269
+ * Middleware wrapper that enriches tool modules with authentication context.
270
+ *
271
+ * Wraps plain tool modules to inject authentication, logging, and request metadata.
272
+ * The wrapper pattern allows separation of business logic from cross-cutting concerns.
273
+ *
274
+ * @template TArgs - Tool arguments type (inferred from tool module)
275
+ * @template TExtra - Enriched extra type with auth context and logger
276
+ *
277
+ * @param toolModule - Plain tool module to wrap with auth middleware
278
+ * @returns Wrapped tool module with enriched handler signature
279
+ *
280
+ * @remarks
281
+ * Auth middleware wrappers typically:
282
+ * - Extract auth context from MCP request or OAuth provider
283
+ * - Inject logger instance for structured logging
284
+ * - Handle authentication errors with proper MCP error responses
285
+ * - Preserve tool configuration and metadata
286
+ *
287
+ * @example
288
+ * ```typescript
289
+ * // Actual usage pattern from OAuth providers (LoopbackOAuthProvider, ServiceAccountProvider, DcrOAuthProvider)
290
+ * const provider = new LoopbackOAuthProvider({ service: 'gmail', ... });
291
+ * const authMiddleware = provider.authMiddleware();
292
+ *
293
+ * // Apply middleware to tools (handlers receive enriched extra with authContext)
294
+ * const tools = toolFactories.map(f => f()).map(authMiddleware.withToolAuth);
295
+ * const resources = resourceFactories.map(f => f()).map(authMiddleware.withResourceAuth);
296
+ * const prompts = promptFactories.map(f => f()).map(authMiddleware.withPromptAuth);
297
+ *
298
+ * // Tool handler receives enriched extra with guaranteed authContext
299
+ * async function handler({ id }: In, extra: EnrichedExtra) {
300
+ * // extra.authContext.auth is OAuth2Client (from middleware)
301
+ * const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });
302
+ * // ... business logic with authenticated context
303
+ * }
304
+ * ```
305
+ *
306
+ * @see {@link ToolModule} for base tool interface
307
+ * @see {@link ToolHandler} for handler function signature
308
+ */
309
+ export type AuthMiddlewareWrapper<TArgs = unknown, TExtra = RequestHandlerExtra<ServerRequest, ServerNotification>> = (toolModule: ToolModule) => ToolModule<ToolConfig, ToolHandler<TArgs, TExtra>>;
310
+ /**
311
+ * Base interface for stateful OAuth adapters (LoopbackOAuthProvider pattern)
312
+ *
313
+ * Stateful adapters manage token storage, refresh, and multi-account state.
314
+ * Used for local development, test setup, and CI/CD workflows.
315
+ *
316
+ * Key characteristics:
317
+ * - Token storage and retrieval via tokenStore
318
+ * - Automatic token refresh with provider
319
+ * - Interactive OAuth flows (browser, ephemeral server)
320
+ * - Multi-account management
321
+ *
322
+ * Parameter usage:
323
+ * - accountId: Account identifier (email address for token storage)
324
+ */
325
+ export interface OAuth2TokenStorageProvider {
326
+ /**
327
+ * Get access token for the specified account.
328
+ * If token is expired, automatically refreshes it.
329
+ * If token is missing, triggers OAuth flow (interactive) or throws AuthRequired (headless).
330
+ *
331
+ * @param accountId - Account identifier for multi-account support
332
+ * @returns Access token string
333
+ */
334
+ getAccessToken(accountId?: string): Promise<string>;
335
+ /**
336
+ * Get email address for the specified account.
337
+ * Used during account registration to verify identity with provider.
338
+ *
339
+ * @param accountId - Account identifier
340
+ * @returns Email address from provider verification
341
+ */
342
+ getUserEmail(accountId?: string): Promise<string>;
343
+ }
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Type definitions for multi-account management and OAuth integration
3
+ */
4
+ import type { AnySchema, ZodRawShapeCompat } from '@modelcontextprotocol/sdk/server/zod-compat.js';
5
+ import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
6
+ import type { CallToolResult, GetPromptResult, ServerNotification, ServerRequest, ToolAnnotations } from '@modelcontextprotocol/sdk/types.js';
7
+ export type Logger = Pick<Console, 'info' | 'error' | 'warn' | 'debug'>;
8
+ export interface AccountInfo {
9
+ email: string;
10
+ alias?: string;
11
+ addedAt: string;
12
+ lastUsed?: string;
13
+ metadata?: {
14
+ name?: string;
15
+ picture?: string;
16
+ [key: string]: unknown;
17
+ };
18
+ }
19
+ /**
20
+ * MCP tool module definition with configuration and handler function.
21
+ *
22
+ * Represents a registered tool in the Model Context Protocol server that can be
23
+ * invoked by MCP clients. Tools are the primary mechanism for executing operations
24
+ * in response to client requests.
25
+ *
26
+ * @property name - Unique tool identifier (e.g., "gmail-message-send", "sheets-values-get")
27
+ * @property config - Tool configuration including description and schemas
28
+ * @property config.description - Human-readable description shown to MCP clients
29
+ * @property config.inputSchema - Zod schema defining tool arguments (JSON-serializable)
30
+ * @property config.outputSchema - Zod schema defining tool response structure
31
+ * @property handler - Async function that executes the tool operation
32
+ *
33
+ * @remarks
34
+ * This is the runtime representation of an MCP tool after registration. The handler
35
+ * receives JSON-serializable arguments validated against inputSchema and returns
36
+ * a CallToolResult validated against outputSchema.
37
+ *
38
+ * Tools are typically created using tool factory functions and registered with the
39
+ * MCP server during initialization.
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * const tool: McpTool = {
44
+ * name: "gmail-message-send",
45
+ * config: {
46
+ * description: "Send an email message",
47
+ * inputSchema: { to: { type: "string" }, subject: { type: "string" } },
48
+ * outputSchema: { result: { type: "object" } }
49
+ * },
50
+ * handler: async (args, context) => {
51
+ * // Implementation
52
+ * return { content: [{ type: "text", text: "Message sent" }] };
53
+ * }
54
+ * };
55
+ * ```
56
+ *
57
+ * @see {@link McpPrompt} for prompt module definition
58
+ */
59
+ export interface McpTool {
60
+ name: string;
61
+ config: {
62
+ description: string;
63
+ inputSchema: Record<string, unknown>;
64
+ outputSchema: Record<string, unknown>;
65
+ };
66
+ handler: (args: unknown, context?: unknown) => Promise<CallToolResult>;
67
+ }
68
+ /**
69
+ * MCP prompt module definition with configuration and handler function.
70
+ *
71
+ * Represents a registered prompt template in the Model Context Protocol server that
72
+ * can be retrieved and rendered by MCP clients. Prompts provide reusable templates
73
+ * for common interaction patterns.
74
+ *
75
+ * @property name - Unique prompt identifier (e.g., "draft-email", "summarize-thread")
76
+ * @property config - Prompt configuration (schema and metadata are prompt-specific)
77
+ * @property handler - Async function that generates the prompt content
78
+ *
79
+ * @remarks
80
+ * This is the runtime representation of an MCP prompt after registration. Unlike
81
+ * {@link McpTool} which executes operations, prompts generate templated content
82
+ * that clients can use to structure interactions.
83
+ *
84
+ * The handler receives optional arguments and returns a GetPromptResult containing
85
+ * the rendered prompt messages.
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * const prompt: McpPrompt = {
90
+ * name: "draft-email",
91
+ * config: {
92
+ * description: "Generate email draft from key points",
93
+ * arguments: [{ name: "points", description: "Key points to include" }]
94
+ * },
95
+ * handler: async (args) => {
96
+ * const points = args?.points || [];
97
+ * return {
98
+ * messages: [{
99
+ * role: "user",
100
+ * content: { type: "text", text: `Draft email covering: ${points.join(", ")}` }
101
+ * }]
102
+ * };
103
+ * }
104
+ * };
105
+ * ```
106
+ *
107
+ * @see {@link McpTool} for tool module definition
108
+ */
109
+ export interface McpPrompt {
110
+ name: string;
111
+ config: unknown;
112
+ handler: (args: unknown) => Promise<GetPromptResult>;
113
+ }
114
+ export declare class AccountManagerError extends Error {
115
+ code: string;
116
+ retryable: boolean;
117
+ constructor(message: string, code: string, retryable?: boolean);
118
+ }
119
+ export declare class AccountNotFoundError extends AccountManagerError {
120
+ constructor(accountRef: string);
121
+ }
122
+ export declare class ConfigurationError extends AccountManagerError {
123
+ constructor(message: string);
124
+ }
125
+ export declare class RequiresAuthenticationError extends AccountManagerError {
126
+ accountId: string | undefined;
127
+ constructor(service: string, accountId?: string);
128
+ }
129
+ export interface AuthEmailProvider {
130
+ getUserEmail(accountId?: string): Promise<string>;
131
+ authenticateNewAccount?(): Promise<string>;
132
+ }
133
+ export interface UserAuthProvider {
134
+ getUserId(req: unknown): Promise<string>;
135
+ }
136
+ export interface JWTUserAuthConfig {
137
+ secret?: string;
138
+ publicKey?: string | object;
139
+ jwksUrl?: string;
140
+ issuer?: string | string[];
141
+ audience?: string | string[];
142
+ userIdClaim?: string;
143
+ algorithms?: string[];
144
+ clockTolerance?: number;
145
+ }
146
+ export interface SessionUserAuthConfig {
147
+ sessionSecret: string;
148
+ cookieName?: string;
149
+ algorithm?: 'sha256' | 'sha512';
150
+ }
151
+ export interface Credentials {
152
+ accessToken: string;
153
+ expiresAt?: number;
154
+ refreshToken?: string;
155
+ scope?: string;
156
+ tokenType?: string;
157
+ idToken?: string;
158
+ }
159
+ export type AuthFlowDescriptor = {
160
+ kind: 'credentials';
161
+ connection?: string;
162
+ provider?: string;
163
+ credentials: Credentials;
164
+ } | {
165
+ kind: 'auth_url';
166
+ connection?: string;
167
+ provider?: string;
168
+ url: string;
169
+ txn?: string;
170
+ state?: string;
171
+ codeVerifier?: string;
172
+ poll?: {
173
+ statusUrl: string;
174
+ interval?: number;
175
+ };
176
+ hint?: string;
177
+ } | {
178
+ kind: 'device_code';
179
+ connection?: string;
180
+ provider?: string;
181
+ txn?: string;
182
+ device: {
183
+ userCode: string;
184
+ verificationUri: string;
185
+ verificationUriComplete?: string;
186
+ expiresIn: number;
187
+ interval: number;
188
+ };
189
+ poll?: {
190
+ statusUrl: string;
191
+ interval?: number;
192
+ };
193
+ hint?: string;
194
+ } | {
195
+ kind: 'error';
196
+ error: string;
197
+ code?: number;
198
+ };
199
+ export declare class AuthRequiredError extends Error {
200
+ descriptor: AuthFlowDescriptor;
201
+ constructor(descriptor: AuthFlowDescriptor, message?: string);
202
+ }
203
+ export interface CachedToken {
204
+ accessToken: string;
205
+ refreshToken?: string;
206
+ expiresAt?: number;
207
+ scope?: string;
208
+ }
209
+ /**
210
+ * Tool config signature - explicit structural type mirroring SDK registerTool config
211
+ *
212
+ * Uses explicit structure instead of Parameters<> extraction to avoid TypeScript inference
213
+ * collapse to 'never' when using ToolModule[] arrays. The deep conditional types from
214
+ * Parameters<> cannot be unified across array elements.
215
+ *
216
+ * Validated against SDK signature for compatibility - compile errors if SDK changes.
217
+ *
218
+ * NOTE: This type is duplicated in @mcp-z/server for architectural independence.
219
+ * Keep these definitions synchronized manually when updating.
220
+ */
221
+ export type ToolConfig = {
222
+ title?: string;
223
+ description?: string;
224
+ inputSchema?: ZodRawShapeCompat | AnySchema;
225
+ outputSchema?: ZodRawShapeCompat | AnySchema;
226
+ annotations?: ToolAnnotations;
227
+ _meta?: Record<string, unknown>;
228
+ };
229
+ /**
230
+ * Tool handler signature with generic support for middleware.
231
+ *
232
+ * @template TArgs - Tool arguments type (default: unknown for SDK compatibility)
233
+ * @template TExtra - Request handler extra type (default: RequestHandlerExtra from SDK)
234
+ *
235
+ * Defaults provide SDK-extracted types for compatibility with MCP SDK.
236
+ * Generic parameters enable type-safe middleware transformation.
237
+ *
238
+ * NOTE: This interface is duplicated in @mcp-z/server for architectural independence.
239
+ * Keep these definitions synchronized manually when updating.
240
+ */
241
+ export type ToolHandler<TArgs = unknown, TExtra = RequestHandlerExtra<ServerRequest, ServerNotification>> = (args: TArgs, extra: TExtra) => Promise<CallToolResult>;
242
+ /**
243
+ * Tool module interface with bounded generics.
244
+ *
245
+ * @template TConfig - Tool config type (default: SDK ToolConfig)
246
+ * @template THandler - Handler function type (default: SDK ToolHandler)
247
+ *
248
+ * Use without generics for SDK-typed tools:
249
+ * - Business tool factories: `ToolModule`
250
+ * - Tool registration: `ToolModule[]`
251
+ *
252
+ * Use with generics for middleware transformation:
253
+ * - Auth middleware: `ToolModule<ToolConfig, ToolHandler<TArgs, EnrichedExtra>>`
254
+ *
255
+ * The bounds ensure compatibility with SDK registration.
256
+ *
257
+ * NOTE: This interface is duplicated in @mcp-z/server for architectural independence.
258
+ * Keep these definitions synchronized manually when updating.
259
+ *
260
+ * @see {@link ToolHandler} for handler function signature
261
+ * @see {@link AuthMiddlewareWrapper} for middleware wrapper pattern
262
+ */
263
+ export interface ToolModule<TConfig = ToolConfig, THandler = unknown> {
264
+ name: string;
265
+ config: TConfig;
266
+ handler: THandler;
267
+ }
268
+ /**
269
+ * Middleware wrapper that enriches tool modules with authentication context.
270
+ *
271
+ * Wraps plain tool modules to inject authentication, logging, and request metadata.
272
+ * The wrapper pattern allows separation of business logic from cross-cutting concerns.
273
+ *
274
+ * @template TArgs - Tool arguments type (inferred from tool module)
275
+ * @template TExtra - Enriched extra type with auth context and logger
276
+ *
277
+ * @param toolModule - Plain tool module to wrap with auth middleware
278
+ * @returns Wrapped tool module with enriched handler signature
279
+ *
280
+ * @remarks
281
+ * Auth middleware wrappers typically:
282
+ * - Extract auth context from MCP request or OAuth provider
283
+ * - Inject logger instance for structured logging
284
+ * - Handle authentication errors with proper MCP error responses
285
+ * - Preserve tool configuration and metadata
286
+ *
287
+ * @example
288
+ * ```typescript
289
+ * // Actual usage pattern from OAuth providers (LoopbackOAuthProvider, ServiceAccountProvider, DcrOAuthProvider)
290
+ * const provider = new LoopbackOAuthProvider({ service: 'gmail', ... });
291
+ * const authMiddleware = provider.authMiddleware();
292
+ *
293
+ * // Apply middleware to tools (handlers receive enriched extra with authContext)
294
+ * const tools = toolFactories.map(f => f()).map(authMiddleware.withToolAuth);
295
+ * const resources = resourceFactories.map(f => f()).map(authMiddleware.withResourceAuth);
296
+ * const prompts = promptFactories.map(f => f()).map(authMiddleware.withPromptAuth);
297
+ *
298
+ * // Tool handler receives enriched extra with guaranteed authContext
299
+ * async function handler({ id }: In, extra: EnrichedExtra) {
300
+ * // extra.authContext.auth is OAuth2Client (from middleware)
301
+ * const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });
302
+ * // ... business logic with authenticated context
303
+ * }
304
+ * ```
305
+ *
306
+ * @see {@link ToolModule} for base tool interface
307
+ * @see {@link ToolHandler} for handler function signature
308
+ */
309
+ export type AuthMiddlewareWrapper<TArgs = unknown, TExtra = RequestHandlerExtra<ServerRequest, ServerNotification>> = (toolModule: ToolModule) => ToolModule<ToolConfig, ToolHandler<TArgs, TExtra>>;
310
+ /**
311
+ * Base interface for stateful OAuth adapters (LoopbackOAuthProvider pattern)
312
+ *
313
+ * Stateful adapters manage token storage, refresh, and multi-account state.
314
+ * Used for local development, test setup, and CI/CD workflows.
315
+ *
316
+ * Key characteristics:
317
+ * - Token storage and retrieval via tokenStore
318
+ * - Automatic token refresh with provider
319
+ * - Interactive OAuth flows (browser, ephemeral server)
320
+ * - Multi-account management
321
+ *
322
+ * Parameter usage:
323
+ * - accountId: Account identifier (email address for token storage)
324
+ */
325
+ export interface OAuth2TokenStorageProvider {
326
+ /**
327
+ * Get access token for the specified account.
328
+ * If token is expired, automatically refreshes it.
329
+ * If token is missing, triggers OAuth flow (interactive) or throws AuthRequired (headless).
330
+ *
331
+ * @param accountId - Account identifier for multi-account support
332
+ * @returns Access token string
333
+ */
334
+ getAccessToken(accountId?: string): Promise<string>;
335
+ /**
336
+ * Get email address for the specified account.
337
+ * Used during account registration to verify identity with provider.
338
+ *
339
+ * @param accountId - Account identifier
340
+ * @returns Email address from provider verification
341
+ */
342
+ getUserEmail(accountId?: string): Promise<string>;
343
+ }