import { Request, Response, NextFunction } from 'express'; /** * JSON Schema definition for input validation */ export interface JSONSchema { type: string; properties?: Record; required?: string[]; [key: string]: any; } export type CredentialFieldType = | 'string' | 'number' | 'boolean' | 'object' | 'array' | 'date' | 'file' | 'binary'; export type CredentialFieldConfigType = | 'jwt' | 'bearer' | 'basic' | 'oauth' | 'oidc' | 'keyValue'; export interface CredentialFieldConfig { type?: CredentialFieldConfigType; inject?: any; [key: string]: any; } export interface CredentialFieldDefinition { name: string; description?: string; type: CredentialFieldType; required?: boolean; default?: any; innerFields?: CredentialFieldDefinition[]; or?: CredentialFieldDefinition[]; config?: CredentialFieldConfig; metadata?: Record; } /** * Authentication context passed to handlers */ export interface AuthContext { userId: string; [key: string]: any; } /** * Authentication handler function */ export type AuthenticateFunction = (req: Request) => Promise; /** * Logger interface */ export interface Logger { debug(message: string, meta?: any): void; info(message: string, meta?: any): void; warn(message: string, meta?: any): void; error(message: string, meta?: any): void; } /** * Key-value store interface for persistence */ export interface KeyValueStore { /** * Get value by key * @returns Value as string, or null if not found */ get(key: string): Promise; /** * Set value with optional TTL * @param key - Key to set * @param value - Value (will be JSON stringified) * @param ttl - Time to live in seconds (optional) */ set(key: string, value: string, ttl?: number): Promise; /** * Delete key */ delete(key: string): Promise; /** * Scan keys by pattern (optional, for debugging) * @param pattern - Glob pattern (e.g., "subscription:*") */ scan?(pattern: string): Promise; } /** * Tool handler function */ export type ToolHandler = ( input: TInput, context: AuthContext ) => Promise; /** * Tool definition */ export interface ToolDefinition { name: string; description: string; inputSchema: JSONSchema; handler: ToolHandler; } /** * Resource list item */ export type ResourceCategory = | 'table' | 'file' | 'document' | 'stream' | 'queue' | 'service' | 'topic'; export interface ResourceSchemaColumn { name: string; type: string; nullable?: boolean; isPrimaryKey?: boolean; description?: string; example?: any; metadata?: Record; } export interface ResourceSchema { columns?: ResourceSchemaColumn[]; primaryKey?: string[]; idField?: string; encoding?: string; partitionKeys?: string[]; sampleUri?: string; metadata?: Record; } export interface ResourceChangeModel { mode: 'row' | 'object' | 'file' | 'custom'; identifierField?: string; supportsDiff?: boolean; payloadSchema?: JSONSchema; description?: string; metadata?: Record; } export interface ResourceAccessDetails { classifications?: string[]; sensitivity?: 'public' | 'internal' | 'confidential' | 'restricted'; owners?: string[]; tags?: string[]; metadata?: Record; } export interface ResourceCacheStrategy { recommendedTtlSeconds?: number; supportsIncremental?: boolean; requiresFullRefresh?: boolean; metadata?: Record; } export interface ResourceMetadata { resourceType: ResourceCategory; schema?: ResourceSchema; changeModel?: ResourceChangeModel; access?: ResourceAccessDetails; cache?: ResourceCacheStrategy; sourceSystem?: string; sourceLocation?: string; notes?: string; metadata?: Record; [key: string]: any; } export interface ResourceListItem { uri: string; name: string; description?: string; mimeType?: string; metadata?: ResourceMetadata; } /** * Resource read result */ /** * Pagination metadata for responses */ export interface PaginationMetadata { page: number; limit: number; total?: number; hasMore?: boolean; nextCursor?: string; prevCursor?: string; } /** * Resource read result with optional pagination */ export interface ResourceReadResult { contents: TData; metadata?: ResourceMetadata; pagination?: PaginationMetadata; nextCursor?: string; nextCursorUrl?: string; } /** * Resource list result with optional pagination */ export interface ResourceListResult { resources: ResourceListItem[]; pagination?: PaginationMetadata; nextCursor?: string; } /** * Resource read options */ export interface ResourceReadOptions { pagination?: { page?: number; limit?: number; cursor?: string; }; } /** * Subscription metadata returned by onSubscribe */ export interface SubscriptionMetadata { thirdPartyWebhookId: string; metadata?: Record; } /** * Webhook change information */ export interface WebhookChangeInfo { resourceUri: string; changeType: 'created' | 'updated' | 'deleted'; data?: any; } /** * Resource subscription handlers */ export interface ResourceSubscription { /** * Called when a client subscribes to a resource */ onSubscribe: ( uri: string, subscriptionId: string, thirdPartyWebhookUrl: string, context: AuthContext ) => Promise; /** * Called when a client unsubscribes */ onUnsubscribe: ( uri: string, subscriptionId: string, storedData: SubscriptionMetadata, context: AuthContext ) => Promise; /** * Called when third-party webhook is received */ onWebhook: ( subscriptionId: string, payload: any, headers: Record ) => Promise; } /** * Resource definition */ export interface ResourceDefinition { uri: string; name: string; description: string; mimeType?: string; metadata?: ResourceMetadata; getMetadata?: (uri: string, context: AuthContext) => Promise; read: ( uri: string, context: AuthContext, options?: ResourceReadOptions ) => Promise>; list?: ( context: AuthContext, options?: ResourceReadOptions ) => Promise; subscription?: ResourceSubscription; /** * Optional completion handler for resource URI parameters */ completion?: CompletionHandler; } /** * Completion item returned by completion handlers */ export interface CompletionItem { value: string; label?: string; description?: string; type?: 'value' | 'function' | 'variable' | 'constant' | 'other'; } /** * Completion reference - identifies what to complete */ export type CompletionRef = | { type: 'ref/prompt'; name: string; arguments?: Record; } | { type: 'ref/resource'; uri: string; }; /** * Completion handler function */ export type CompletionHandler = ( ref: CompletionRef, argument: string, context: AuthContext ) => Promise; /** * Prompt definition */ export interface PromptDefinition { name: string; description: string; arguments?: Array<{ name: string; description: string; required?: boolean; }>; handler: (args: Record, context: AuthContext) => Promise<{ messages: Array<{ role: 'user' | 'assistant'; content: string; }>; }>; /** * Optional completion handler for prompt arguments */ completion?: CompletionHandler; } /** * Webhook configuration */ export interface WebhookConfig { incomingPath?: string; incomingSecret?: string; verifyIncomingSignature?: (payload: any, signature: string, secret: string) => boolean; outgoing?: { timeout?: number; retries?: number; retryDelay?: number; signPayload?: (payload: any, secret: string) => string; onBeforeCall?: (url: string, payload: any) => void; onAfterCall?: (url: string, response: any, error?: any) => void; }; } /** * Metrics configuration */ export interface MetricsConfig { enabled: boolean; registry?: any; // prom-client Registry } /** * Tracing configuration */ export interface TracingConfig { enabled: boolean; serviceName?: string; } /** * Batch configuration */ export interface BatchConfig { maxBatchSize?: number; batchTimeout?: number; } /** * Cache configuration */ export interface CacheConfig { enabled: boolean; ttl?: number; keyPrefix?: string; } /** * Dead letter queue configuration */ export interface DeadLetterQueueConfig { enabled: boolean; store: KeyValueStore; retention?: number; maxRetries?: number; } /** * Middleware function */ export type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise; /** * MCP Server configuration */ export interface MCPServerConfig { // Server Identity name: string; version: string; // HTTP Server Configuration port?: number; host?: string; basePath?: string; publicUrl: string; // Authentication authenticate?: AuthenticateFunction; // Core MCP Components tools: ToolDefinition[]; resources: ResourceDefinition[]; prompts?: PromptDefinition[]; // Completions completions?: CompletionHandler; // Storage store: KeyValueStore; // Webhook Configuration webhooks?: WebhookConfig; // Advanced Features batch?: BatchConfig; cache?: CacheConfig; metrics?: MetricsConfig; tracing?: TracingConfig; middleware?: Middleware[]; // Logging logger?: Logger; logLevel?: 'debug' | 'info' | 'warn' | 'error'; credentials?: CredentialFieldDefinition[]; } /** * Stored subscription data */ export interface StoredSubscription { uri: string; resourceType: string; clientCallbackUrl: string; clientCallbackSecret?: string; userId: string; thirdPartyWebhookId: string; metadata?: any; source?: string; // e.g. 'kdl', 'trigger' — scopes cleanup to same source createdAt: number; } /** * MCP Error codes */ export enum MCPErrorCode { AuthenticationError = -32001, ValidationError = -32002, ResourceNotFoundError = -32003, ToolExecutionError = -32004, WebhookError = -32005, StorageError = -32006, } /** * MCP Server instance */ export interface MCPServer { start(): Promise; stop(): Promise; getApp(): any; // Express app }