@openconductor/mcp-sdk 1.0.1 → 1.1.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.
- package/README.md +43 -16
- package/dist/errors/index.d.mts +29 -1
- package/dist/errors/index.d.ts +29 -1
- package/dist/errors/index.js +38 -1
- package/dist/errors/index.js.map +1 -1
- package/dist/errors/index.mjs +36 -2
- package/dist/errors/index.mjs.map +1 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +204 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +196 -2
- package/dist/index.mjs.map +1 -1
- package/dist/payment/index.d.mts +137 -0
- package/dist/payment/index.d.ts +137 -0
- package/dist/payment/index.js +253 -0
- package/dist/payment/index.js.map +1 -0
- package/dist/payment/index.mjs +246 -0
- package/dist/payment/index.mjs.map +1 -0
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs.map +1 -1
- package/dist/validate/index.js.map +1 -1
- package/dist/validate/index.mjs.map +1 -1
- package/package.json +11 -3
package/dist/index.mjs
CHANGED
|
@@ -19,7 +19,10 @@ var ErrorCodes = {
|
|
|
19
19
|
TIMEOUT_ERROR: -32007,
|
|
20
20
|
VALIDATION_ERROR: -32008,
|
|
21
21
|
DEPENDENCY_ERROR: -32009,
|
|
22
|
-
CONFIGURATION_ERROR: -32010
|
|
22
|
+
CONFIGURATION_ERROR: -32010,
|
|
23
|
+
PAYMENT_REQUIRED: -32011,
|
|
24
|
+
INSUFFICIENT_CREDITS: -32012,
|
|
25
|
+
SUBSCRIPTION_REQUIRED: -32013
|
|
23
26
|
};
|
|
24
27
|
|
|
25
28
|
// src/errors/index.ts
|
|
@@ -143,6 +146,37 @@ var ConfigurationError = class extends MCPError {
|
|
|
143
146
|
this.name = "ConfigurationError";
|
|
144
147
|
}
|
|
145
148
|
};
|
|
149
|
+
var PaymentRequiredError = class extends MCPError {
|
|
150
|
+
constructor(toolName, options) {
|
|
151
|
+
super(ErrorCodes.PAYMENT_REQUIRED, `Payment required to use '${toolName}'`, {
|
|
152
|
+
tool: toolName,
|
|
153
|
+
...options?.upgradeUrl && { upgradeUrl: options.upgradeUrl },
|
|
154
|
+
...options?.priceId && { priceId: options.priceId }
|
|
155
|
+
});
|
|
156
|
+
this.name = "PaymentRequiredError";
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
var InsufficientCreditsError = class extends MCPError {
|
|
160
|
+
constructor(required, available, options) {
|
|
161
|
+
super(ErrorCodes.INSUFFICIENT_CREDITS, `Insufficient credits: need ${required}, have ${available}`, {
|
|
162
|
+
required,
|
|
163
|
+
available,
|
|
164
|
+
...options?.purchaseUrl && { purchaseUrl: options.purchaseUrl }
|
|
165
|
+
});
|
|
166
|
+
this.name = "InsufficientCreditsError";
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
var SubscriptionRequiredError = class extends MCPError {
|
|
170
|
+
constructor(requiredTier, currentTier, options) {
|
|
171
|
+
const msg = currentTier ? `Subscription '${requiredTier}' required (current: '${currentTier}')` : `Subscription '${requiredTier}' required`;
|
|
172
|
+
super(ErrorCodes.SUBSCRIPTION_REQUIRED, msg, {
|
|
173
|
+
requiredTier,
|
|
174
|
+
...currentTier && { currentTier },
|
|
175
|
+
...options?.upgradeUrl && { upgradeUrl: options.upgradeUrl }
|
|
176
|
+
});
|
|
177
|
+
this.name = "SubscriptionRequiredError";
|
|
178
|
+
}
|
|
179
|
+
};
|
|
146
180
|
function validate(schema, input, options = {}) {
|
|
147
181
|
const { stripUnknown = true } = options;
|
|
148
182
|
const result = stripUnknown ? schema.safeParse(input) : schema instanceof z.ZodObject ? schema.strict().safeParse(input) : schema.safeParse(input);
|
|
@@ -490,6 +524,166 @@ function sanitizeInput(input) {
|
|
|
490
524
|
return sanitized;
|
|
491
525
|
}
|
|
492
526
|
|
|
493
|
-
|
|
527
|
+
// src/payment/index.ts
|
|
528
|
+
var paymentConfig = null;
|
|
529
|
+
function initPayment(config) {
|
|
530
|
+
paymentConfig = {
|
|
531
|
+
apiUrl: "https://api.openconductor.ai",
|
|
532
|
+
testMode: false,
|
|
533
|
+
...config
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
function getPaymentConfig() {
|
|
537
|
+
return paymentConfig;
|
|
538
|
+
}
|
|
539
|
+
async function checkBilling(params) {
|
|
540
|
+
const config = paymentConfig;
|
|
541
|
+
if (!config) {
|
|
542
|
+
throw new ConfigurationError("payment", "Payment not initialized. Call initPayment() first.");
|
|
543
|
+
}
|
|
544
|
+
if (config.testMode) {
|
|
545
|
+
return { allowed: true, credits: 9999, tier: "test" };
|
|
546
|
+
}
|
|
547
|
+
try {
|
|
548
|
+
const response = await fetch(`${config.apiUrl}/v1/billing/check`, {
|
|
549
|
+
method: "POST",
|
|
550
|
+
headers: {
|
|
551
|
+
"Content-Type": "application/json",
|
|
552
|
+
"Authorization": `Bearer ${config.apiKey}`
|
|
553
|
+
},
|
|
554
|
+
body: JSON.stringify({
|
|
555
|
+
userId: params.userId,
|
|
556
|
+
requirement: params.requirement,
|
|
557
|
+
tool: params.toolName
|
|
558
|
+
})
|
|
559
|
+
});
|
|
560
|
+
if (!response.ok) {
|
|
561
|
+
const errorBody = await response.text();
|
|
562
|
+
console.error("[payment] Billing check failed:", response.status, errorBody);
|
|
563
|
+
return {
|
|
564
|
+
allowed: false,
|
|
565
|
+
reason: "Billing service unavailable",
|
|
566
|
+
actionUrl: config.upgradeUrl
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
return await response.json();
|
|
570
|
+
} catch (error) {
|
|
571
|
+
console.error("[payment] Billing check error:", error);
|
|
572
|
+
return {
|
|
573
|
+
allowed: false,
|
|
574
|
+
reason: "Unable to verify billing status",
|
|
575
|
+
actionUrl: config.upgradeUrl
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
async function deductCredits(params) {
|
|
580
|
+
const config = paymentConfig;
|
|
581
|
+
if (!config) return false;
|
|
582
|
+
if (config.testMode) return true;
|
|
583
|
+
try {
|
|
584
|
+
const response = await fetch(`${config.apiUrl}/v1/billing/deduct`, {
|
|
585
|
+
method: "POST",
|
|
586
|
+
headers: {
|
|
587
|
+
"Content-Type": "application/json",
|
|
588
|
+
"Authorization": `Bearer ${config.apiKey}`
|
|
589
|
+
},
|
|
590
|
+
body: JSON.stringify({
|
|
591
|
+
userId: params.userId,
|
|
592
|
+
credits: params.credits,
|
|
593
|
+
tool: params.toolName,
|
|
594
|
+
callId: params.callId
|
|
595
|
+
})
|
|
596
|
+
});
|
|
597
|
+
return response.ok;
|
|
598
|
+
} catch (error) {
|
|
599
|
+
console.error("[payment] Credit deduction error:", error);
|
|
600
|
+
return false;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
function isCreditRequirement(req) {
|
|
604
|
+
return "credits" in req && typeof req.credits === "number";
|
|
605
|
+
}
|
|
606
|
+
function isSubscriptionRequirement(req) {
|
|
607
|
+
return "tier" in req && typeof req.tier === "string";
|
|
608
|
+
}
|
|
609
|
+
function isStripeRequirement(req) {
|
|
610
|
+
return "priceId" in req && typeof req.priceId === "string";
|
|
611
|
+
}
|
|
612
|
+
function requirePayment(requirement, options = {}) {
|
|
613
|
+
return (handler) => {
|
|
614
|
+
const { toolName = "unknown", getUserId } = options;
|
|
615
|
+
return async (input) => {
|
|
616
|
+
const userId = getUserId?.(input) ?? input.userId;
|
|
617
|
+
if (!userId) {
|
|
618
|
+
throw new PaymentRequiredError(toolName, {
|
|
619
|
+
upgradeUrl: paymentConfig?.upgradeUrl
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
const status = await checkBilling({
|
|
623
|
+
userId,
|
|
624
|
+
requirement,
|
|
625
|
+
toolName
|
|
626
|
+
});
|
|
627
|
+
if (!status.allowed) {
|
|
628
|
+
if (isCreditRequirement(requirement)) {
|
|
629
|
+
throw new InsufficientCreditsError(
|
|
630
|
+
requirement.credits,
|
|
631
|
+
status.credits ?? 0,
|
|
632
|
+
{ purchaseUrl: status.actionUrl }
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
if (isSubscriptionRequirement(requirement)) {
|
|
636
|
+
throw new SubscriptionRequiredError(
|
|
637
|
+
requirement.tier,
|
|
638
|
+
status.tier,
|
|
639
|
+
{ upgradeUrl: status.actionUrl }
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
throw new PaymentRequiredError(toolName, {
|
|
643
|
+
upgradeUrl: status.actionUrl,
|
|
644
|
+
...isStripeRequirement(requirement) && { priceId: requirement.priceId }
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
const result = await handler(input);
|
|
648
|
+
if (isCreditRequirement(requirement)) {
|
|
649
|
+
await deductCredits({
|
|
650
|
+
userId,
|
|
651
|
+
credits: requirement.credits,
|
|
652
|
+
toolName
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
return result;
|
|
656
|
+
};
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
function createPaidTool(config) {
|
|
660
|
+
return requirePayment(config.payment, {
|
|
661
|
+
toolName: config.name,
|
|
662
|
+
getUserId: config.getUserId
|
|
663
|
+
})(config.handler);
|
|
664
|
+
}
|
|
665
|
+
async function canUserAccess(userId, requirement, toolName = "check") {
|
|
666
|
+
return checkBilling({ userId, requirement, toolName });
|
|
667
|
+
}
|
|
668
|
+
async function getUserBillingStatus(userId) {
|
|
669
|
+
const config = paymentConfig;
|
|
670
|
+
if (!config) return null;
|
|
671
|
+
if (config.testMode) {
|
|
672
|
+
return { credits: 9999, tier: "test", active: true };
|
|
673
|
+
}
|
|
674
|
+
try {
|
|
675
|
+
const response = await fetch(`${config.apiUrl}/v1/billing/status/${userId}`, {
|
|
676
|
+
headers: {
|
|
677
|
+
"Authorization": `Bearer ${config.apiKey}`
|
|
678
|
+
}
|
|
679
|
+
});
|
|
680
|
+
if (!response.ok) return null;
|
|
681
|
+
return await response.json();
|
|
682
|
+
} catch {
|
|
683
|
+
return null;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
export { AuthenticationError, AuthorizationError, ConfigurationError, DependencyError, ErrorCodes, InsufficientCreditsError, MCPError, PaymentRequiredError, RateLimitError, ResourceNotFoundError, SubscriptionRequiredError, Telemetry, TimeoutError, ToolExecutionError, ToolNotFoundError, ValidationError, canUserAccess, createHealthCheck, createLogger, createPaidTool, getPaymentConfig, getTelemetry, getUserBillingStatus, initPayment, initTelemetry, requirePayment, schemas, validate, validateInput, wrapTool };
|
|
494
688
|
//# sourceMappingURL=index.mjs.map
|
|
495
689
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors/codes.ts","../src/errors/index.ts","../src/validate/index.ts","../src/logger/index.ts","../src/telemetry/index.ts","../src/server/index.ts"],"names":[],"mappings":";;;;AAIO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,WAAA,EAAa,MAAA;AAAA,EACb,eAAA,EAAiB,MAAA;AAAA,EACjB,gBAAA,EAAkB,MAAA;AAAA,EAClB,cAAA,EAAgB,MAAA;AAAA,EAChB,cAAA,EAAgB,MAAA;AAAA;AAAA,EAGhB,cAAA,EAAgB,MAAA;AAAA,EAChB,oBAAA,EAAsB,MAAA;AAAA,EACtB,kBAAA,EAAoB,MAAA;AAAA,EACpB,oBAAA,EAAsB,MAAA;AAAA,EACtB,mBAAA,EAAqB,MAAA;AAAA,EACrB,gBAAA,EAAkB,MAAA;AAAA,EAClB,aAAA,EAAe,MAAA;AAAA,EACf,gBAAA,EAAkB,MAAA;AAAA,EAClB,gBAAA,EAAkB,MAAA;AAAA,EAClB,mBAAA,EAAqB;AACvB;;;ACfO,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA,EAClB,IAAA;AAAA,EACA,IAAA;AAAA,EAEhB,WAAA,CACE,IAAA,EACA,OAAA,EACA,IAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,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index.mjs","sourcesContent":["/**\n * JSON-RPC 2.0 Standard Error Codes\n * https://www.jsonrpc.org/specification#error_object\n */\nexport const ErrorCodes = {\n // JSON-RPC 2.0 Standard Errors\n PARSE_ERROR: -32700,\n INVALID_REQUEST: -32600,\n METHOD_NOT_FOUND: -32601,\n INVALID_PARAMS: -32602,\n INTERNAL_ERROR: -32603,\n\n // MCP-Specific Errors (-32000 to -32099 reserved for implementation)\n TOOL_NOT_FOUND: -32001,\n TOOL_EXECUTION_ERROR: -32002,\n RESOURCE_NOT_FOUND: -32003,\n AUTHENTICATION_ERROR: -32004,\n AUTHORIZATION_ERROR: -32005,\n RATE_LIMIT_ERROR: -32006,\n TIMEOUT_ERROR: -32007,\n VALIDATION_ERROR: -32008,\n DEPENDENCY_ERROR: -32009,\n CONFIGURATION_ERROR: -32010,\n} as const\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes]\n","import { ErrorCodes, type ErrorCode } from './codes'\n\nexport { ErrorCodes, type ErrorCode } from './codes'\n\n/**\n * Base error class for MCP servers\n * Formats errors according to JSON-RPC 2.0 specification\n */\nexport class MCPError extends Error {\n public readonly code: ErrorCode\n public readonly data?: Record<string, unknown>\n\n constructor(\n code: ErrorCode,\n message: string,\n data?: Record<string, unknown>\n ) {\n super(message)\n this.name = 'MCPError'\n this.code = code\n this.data = data\n\n // Maintains proper stack trace in V8 environments\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n\n /**\n * Returns JSON-RPC 2.0 formatted error object\n */\n toJSON() {\n return {\n code: this.code,\n message: this.message,\n ...(this.data && { data: this.data }),\n }\n }\n\n /**\n * Create error response for JSON-RPC\n */\n toResponse(id: string | number | null = null) {\n return {\n jsonrpc: '2.0' as const,\n id,\n error: this.toJSON(),\n }\n }\n}\n\n/**\n * Thrown when tool input validation fails\n */\nexport class ValidationError extends MCPError {\n constructor(field: string, reason: string, value?: unknown) {\n super(ErrorCodes.INVALID_PARAMS, `Validation failed for '${field}': ${reason}`, {\n field,\n reason,\n ...(value !== undefined && { value }),\n })\n this.name = 'ValidationError'\n }\n}\n\n/**\n * Thrown when a requested tool doesn't exist\n */\nexport class ToolNotFoundError extends MCPError {\n constructor(toolName: string) {\n super(ErrorCodes.TOOL_NOT_FOUND, `Tool '${toolName}' not found`, {\n tool: toolName,\n })\n this.name = 'ToolNotFoundError'\n }\n}\n\n/**\n * Thrown when tool execution fails\n */\nexport class ToolExecutionError extends MCPError {\n constructor(toolName: string, reason: string, cause?: Error) {\n super(ErrorCodes.TOOL_EXECUTION_ERROR, `Tool '${toolName}' failed: ${reason}`, {\n tool: toolName,\n reason,\n ...(cause && { cause: cause.message }),\n })\n this.name = 'ToolExecutionError'\n }\n}\n\n/**\n * Thrown when a requested resource doesn't exist\n */\nexport class ResourceNotFoundError extends MCPError {\n constructor(resourceUri: string) {\n super(ErrorCodes.RESOURCE_NOT_FOUND, `Resource '${resourceUri}' not found`, {\n uri: resourceUri,\n })\n this.name = 'ResourceNotFoundError'\n }\n}\n\n/**\n * Thrown when authentication fails\n */\nexport class AuthenticationError extends MCPError {\n constructor(reason: string = 'Authentication required') {\n super(ErrorCodes.AUTHENTICATION_ERROR, reason)\n this.name = 'AuthenticationError'\n }\n}\n\n/**\n * Thrown when authorization fails (authenticated but not permitted)\n */\nexport class AuthorizationError extends MCPError {\n constructor(action: string, resource?: string) {\n const msg = resource\n ? `Not authorized to ${action} on '${resource}'`\n : `Not authorized to ${action}`\n super(ErrorCodes.AUTHORIZATION_ERROR, msg, {\n action,\n ...(resource && { resource }),\n })\n this.name = 'AuthorizationError'\n }\n}\n\n/**\n * Thrown when rate limits are exceeded\n */\nexport class RateLimitError extends MCPError {\n constructor(retryAfterMs?: number) {\n super(ErrorCodes.RATE_LIMIT_ERROR, 'Rate limit exceeded', {\n ...(retryAfterMs && { retryAfterMs }),\n })\n this.name = 'RateLimitError'\n }\n}\n\n/**\n * Thrown when an operation times out\n */\nexport class TimeoutError extends MCPError {\n constructor(operation: string, timeoutMs: number) {\n super(ErrorCodes.TIMEOUT_ERROR, `Operation '${operation}' timed out after ${timeoutMs}ms`, {\n operation,\n timeoutMs,\n })\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a required dependency is unavailable\n */\nexport class DependencyError extends MCPError {\n constructor(dependency: string, reason: string) {\n super(ErrorCodes.DEPENDENCY_ERROR, `Dependency '${dependency}' unavailable: ${reason}`, {\n dependency,\n reason,\n })\n this.name = 'DependencyError'\n }\n}\n\n/**\n * Thrown when server configuration is invalid\n */\nexport class ConfigurationError extends MCPError {\n constructor(setting: string, reason: string) {\n super(ErrorCodes.CONFIGURATION_ERROR, `Invalid configuration '${setting}': ${reason}`, {\n setting,\n reason,\n })\n this.name = 'ConfigurationError'\n }\n}\n","import { z, ZodError, type ZodSchema, type ZodTypeDef, type SafeParseReturnType } from 'zod'\nimport { ValidationError } from '../errors'\n\n// Re-export zod for convenience\nexport { z, ZodError, type ZodSchema }\nexport type { ZodTypeDef }\n\n/**\n * Options for input validation\n */\nexport interface ValidateOptions {\n /** Strip unknown keys from objects (default: true) */\n stripUnknown?: boolean\n /** Custom error formatter */\n formatError?: (error: ZodError) => string\n}\n\n/**\n * Validates input against a Zod schema\n * Throws ValidationError on failure with detailed field info\n */\nexport function validate<T>(\n schema: ZodSchema<T>,\n input: unknown,\n options: ValidateOptions = {}\n): T {\n const { stripUnknown = true } = options\n\n const result = (\n stripUnknown\n ? schema.safeParse(input)\n : schema instanceof z.ZodObject\n ? schema.strict().safeParse(input)\n : schema.safeParse(input)\n ) as SafeParseReturnType<unknown, T>\n\n if (!result.success) {\n const firstError = result.error.errors[0]\n const field = firstError.path.join('.') || 'input'\n const reason = firstError.message\n throw new ValidationError(field, reason, firstError.path.length > 0 \n ? getNestedValue(input, firstError.path) \n : input\n )\n }\n\n return result.data\n}\n\n/**\n * Creates a validated tool handler\n * Wraps your handler function with automatic input validation\n */\nexport function validateInput<TInput, TOutput>(\n schema: ZodSchema<TInput>,\n handler: (input: TInput) => TOutput | Promise<TOutput>,\n options: ValidateOptions = {}\n): (input: unknown) => Promise<TOutput> {\n return async (input: unknown) => {\n const validated = validate(schema, input, options)\n return handler(validated)\n }\n}\n\n\n/**\n * Helper to extract nested value from object by path\n */\nfunction getNestedValue(obj: unknown, path: (string | number)[]): unknown {\n let current = obj\n for (const key of path) {\n if (current === null || current === undefined) return undefined\n current = (current as Record<string | number, unknown>)[key]\n }\n return current\n}\n\n/**\n * Common schema patterns for MCP tools\n */\nexport const schemas = {\n /** Non-empty string */\n nonEmptyString: z.string().min(1, 'Cannot be empty'),\n \n /** Positive integer */\n positiveInt: z.number().int().positive(),\n \n /** Pagination limit (1-100, default 10) */\n limit: z.number().int().min(1).max(100).default(10),\n \n /** Pagination offset (>= 0, default 0) */\n offset: z.number().int().min(0).default(0),\n \n /** URL string */\n url: z.string().url(),\n \n /** Email string */\n email: z.string().email(),\n \n /** UUID string */\n uuid: z.string().uuid(),\n \n /** ISO date string */\n isoDate: z.string().datetime(),\n \n /** Boolean with string coercion ('true'/'false' -> boolean) */\n booleanish: z.union([\n z.boolean(),\n z.enum(['true', 'false']).transform(v => v === 'true'),\n ]),\n}\n\n/**\n * Type helper to infer schema type\n */\nexport type Infer<T extends ZodSchema> = z.infer<T>\n","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n timestamp?: string\n level: LogLevel\n service: string\n message: string\n [key: string]: unknown\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel\n /** Custom output function (default: console methods) */\n output?: (entry: LogEntry) => void\n /** Include timestamps (default: true) */\n timestamps?: boolean\n /** Pretty print JSON (default: false, use true for local dev) */\n pretty?: boolean\n}\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a structured logger for MCP servers\n */\nexport function createLogger(service: string, options: LoggerOptions = {}) {\n const {\n level: minLevel = 'info',\n timestamps = true,\n pretty = false,\n } = options\n\n const shouldLog = (level: LogLevel): boolean => {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel]\n }\n\n const formatEntry = (entry: LogEntry): string => {\n return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry)\n }\n\n const log = (level: LogLevel, message: string, data?: Record<string, unknown>) => {\n if (!shouldLog(level)) return\n\n const entry: LogEntry = {\n ...(timestamps && { timestamp: new Date().toISOString() }),\n level,\n service,\n message,\n ...data,\n }\n\n if (options.output) {\n options.output(entry)\n } else {\n const formatted = formatEntry(entry)\n switch (level) {\n case 'debug':\n console.debug(formatted)\n break\n case 'info':\n console.info(formatted)\n break\n case 'warn':\n console.warn(formatted)\n break\n case 'error':\n console.error(formatted)\n break\n }\n }\n\n return entry\n }\n\n return {\n debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),\n info: (message: string, data?: Record<string, unknown>) => log('info', message, data),\n warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),\n error: (message: string, data?: Record<string, unknown>) => log('error', message, data),\n \n /**\n * Create a child logger with additional context\n */\n child: (context: Record<string, unknown>) => {\n return createLogger(service, {\n ...options,\n output: (entry) => {\n const merged = { ...entry, ...context }\n if (options.output) {\n options.output(merged)\n } else {\n const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged)\n console[entry.level](formatted)\n }\n },\n })\n },\n }\n}\n\nexport type Logger = ReturnType<typeof createLogger>\n","export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '1.0.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n","import { MCPError, ToolExecutionError, TimeoutError } from '../errors'\nimport { createLogger, type Logger } from '../logger'\nimport { getTelemetry } from '../telemetry'\n\nexport interface HealthCheckInfo {\n name: string\n version: string\n description?: string\n uptime?: () => number\n checks?: Record<string, () => Promise<boolean> | boolean>\n}\n\nexport interface HealthCheckResponse {\n status: 'healthy' | 'degraded' | 'unhealthy'\n name: string\n version: string\n description?: string\n uptime?: number\n timestamp: string\n checks?: Record<string, boolean>\n}\n\n/**\n * Creates a standard health check response for MCP servers\n */\nexport function createHealthCheck(info: HealthCheckInfo) {\n return async (): Promise<HealthCheckResponse> => {\n const checks: Record<string, boolean> = {}\n let allHealthy = true\n\n if (info.checks) {\n for (const [name, check] of Object.entries(info.checks)) {\n try {\n checks[name] = await check()\n if (!checks[name]) allHealthy = false\n } catch {\n checks[name] = false\n allHealthy = false\n }\n }\n }\n\n return {\n status: allHealthy ? 'healthy' : 'degraded',\n name: info.name,\n version: info.version,\n ...(info.description && { description: info.description }),\n ...(info.uptime && { uptime: info.uptime() }),\n timestamp: new Date().toISOString(),\n ...(Object.keys(checks).length > 0 && { checks }),\n }\n }\n}\n\n\nexport interface WrapToolOptions {\n /** Tool name for logging and telemetry */\n name: string\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number\n /** Custom logger instance */\n logger?: Logger\n /** Enable telemetry reporting (default: true if telemetry initialized) */\n telemetry?: boolean\n}\n\nexport interface ToolContext {\n /** Unique ID for this tool call */\n callId: string\n /** Tool name */\n name: string\n /** Start time of execution */\n startTime: number\n /** Logger scoped to this call */\n log: Logger\n}\n\n/**\n * Wraps a tool handler with automatic error handling, logging, timeouts, and telemetry\n */\nexport function wrapTool<TInput, TOutput>(\n handler: (input: TInput, ctx: ToolContext) => TOutput | Promise<TOutput>,\n options: WrapToolOptions\n): (input: TInput) => Promise<TOutput> {\n const {\n name,\n timeout = 30000,\n telemetry: enableTelemetry = true,\n } = options\n\n const baseLogger = options.logger ?? createLogger(name)\n\n return async (input: TInput): Promise<TOutput> => {\n const callId = generateCallId()\n const startTime = Date.now()\n const log = baseLogger.child({ callId })\n\n const ctx: ToolContext = { callId, name, startTime, log }\n\n log.info('Tool invoked', { tool: name, input: sanitizeInput(input) })\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(name, timeout))\n }, timeout)\n })\n\n // Race handler against timeout\n const result = await Promise.race([\n Promise.resolve(handler(input, ctx)),\n timeoutPromise,\n ])\n\n const duration = Date.now() - startTime\n log.info('Tool completed', { tool: name, duration })\n\n // Report success to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, true)\n }\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n log.error('Tool failed', { \n tool: name, \n duration, \n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n })\n\n // Report failure to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, false, errorMessage)\n }\n\n // Re-throw MCPErrors as-is, wrap others\n if (error instanceof MCPError) {\n throw error\n }\n\n throw new ToolExecutionError(\n name,\n errorMessage,\n error instanceof Error ? error : undefined\n )\n }\n }\n}\n\n/**\n * Generates a unique call ID\n */\nfunction generateCallId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * Sanitizes input for logging (removes sensitive fields)\n */\nfunction sanitizeInput(input: unknown): unknown {\n if (typeof input !== 'object' || input === null) return input\n\n const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth', 'credential']\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (sensitiveKeys.some(k => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]'\n } else {\n sanitized[key] = value\n }\n }\n\n return sanitized\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors/codes.ts","../src/errors/index.ts","../src/validate/index.ts","../src/logger/index.ts","../src/telemetry/index.ts","../src/server/index.ts","../src/payment/index.ts"],"names":[],"mappings":";;;;AAIO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,WAAA,EAAa,MAAA;AAAA,EACb,eAAA,EAAiB,MAAA;AAAA,EACjB,gBAAA,EAAkB,MAAA;AAAA,EAClB,cAAA,EAAgB,MAAA;AAAA,EAChB,c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D,CAAA;AAAA,MACH;AAEA,MAAA,OAAO,MAAA;AAAA,IACT,CAAA;AAAA,EACF,CAAA;AACF;AAqBO,SAAS,eAA4D,MAAA,EAKpC;AACtC,EAAA,OAAO,cAAA,CAAgC,OAAO,OAAA,EAAS;AAAA,IACrD,UAAU,MAAA,CAAO,IAAA;AAAA,IACjB,WAAW,MAAA,CAAO;AAAA,GACnB,CAAA,CAAE,MAAA,CAAO,OAAO,CAAA;AACnB;AAcA,eAAsB,aAAA,CACpB,MAAA,EACA,WAAA,EACA,QAAA,GAAmB,OAAA,EACK;AACxB,EAAA,OAAO,YAAA,CAAa,EAAE,MAAA,EAAQ,WAAA,EAAa,UAAU,CAAA;AACvD;AAKA,eAAsB,qBAAqB,MAAA,EAIjC;AACR,EAAA,MAAM,MAAA,GAAS,aAAA;AACf,EAAA,IAAI,CAAC,QAAQ,OAAO,IAAA;AAEpB,EAAA,IAAI,OAAO,QAAA,EAAU;AACnB,IAAA,OAAO,EAAE,OAAA,EAAS,IAAA,EAAM,IAAA,EAAM,MAAA,EAAQ,QAAQ,IAAA,EAAK;AAAA,EACrD;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,CAAA,EAAG,OAAO,MAAM,CAAA,mBAAA,EAAsB,MAAM,CAAA,CAAA,EAAI;AAAA,MAC3E,OAAA,EAAS;AAAA,QACP,eAAA,EAAiB,CAAA,OAAA,EAAU,MAAA,CAAO,MAAM,CAAA;AAAA;AAC1C,KACD,CAAA;AAED,IAAA,IAAI,CAAC,QAAA,CAAS,EAAA,EAAI,OAAO,IAAA;AACzB,IAAA,OAAO,MAAM,SAAS,IAAA,EAAK;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"index.mjs","sourcesContent":["/**\n * JSON-RPC 2.0 Standard Error Codes\n * https://www.jsonrpc.org/specification#error_object\n */\nexport const ErrorCodes = {\n // JSON-RPC 2.0 Standard Errors\n PARSE_ERROR: -32700,\n INVALID_REQUEST: -32600,\n METHOD_NOT_FOUND: -32601,\n INVALID_PARAMS: -32602,\n INTERNAL_ERROR: -32603,\n\n // MCP-Specific Errors (-32000 to -32099 reserved for implementation)\n TOOL_NOT_FOUND: -32001,\n TOOL_EXECUTION_ERROR: -32002,\n RESOURCE_NOT_FOUND: -32003,\n AUTHENTICATION_ERROR: -32004,\n AUTHORIZATION_ERROR: -32005,\n RATE_LIMIT_ERROR: -32006,\n TIMEOUT_ERROR: -32007,\n VALIDATION_ERROR: -32008,\n DEPENDENCY_ERROR: -32009,\n CONFIGURATION_ERROR: -32010,\n PAYMENT_REQUIRED: -32011,\n INSUFFICIENT_CREDITS: -32012,\n SUBSCRIPTION_REQUIRED: -32013,\n} as const\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes]\n","import { ErrorCodes, type ErrorCode } from './codes'\n\nexport { ErrorCodes, type ErrorCode } from './codes'\n\n/**\n * Base error class for MCP servers\n * Formats errors according to JSON-RPC 2.0 specification\n */\nexport class MCPError extends Error {\n public readonly code: ErrorCode\n public readonly data?: Record<string, unknown>\n\n constructor(\n code: ErrorCode,\n message: string,\n data?: Record<string, unknown>\n ) {\n super(message)\n this.name = 'MCPError'\n this.code = code\n this.data = data\n\n // Maintains proper stack trace in V8 environments\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n\n /**\n * Returns JSON-RPC 2.0 formatted error object\n */\n toJSON() {\n return {\n code: this.code,\n message: this.message,\n ...(this.data && { data: this.data }),\n }\n }\n\n /**\n * Create error response for JSON-RPC\n */\n toResponse(id: string | number | null = null) {\n return {\n jsonrpc: '2.0' as const,\n id,\n error: this.toJSON(),\n }\n }\n}\n\n/**\n * Thrown when tool input validation fails\n */\nexport class ValidationError extends MCPError {\n constructor(field: string, reason: string, value?: unknown) {\n super(ErrorCodes.INVALID_PARAMS, `Validation failed for '${field}': ${reason}`, {\n field,\n reason,\n ...(value !== undefined && { value }),\n })\n this.name = 'ValidationError'\n }\n}\n\n/**\n * Thrown when a requested tool doesn't exist\n */\nexport class ToolNotFoundError extends MCPError {\n constructor(toolName: string) {\n super(ErrorCodes.TOOL_NOT_FOUND, `Tool '${toolName}' not found`, {\n tool: toolName,\n })\n this.name = 'ToolNotFoundError'\n }\n}\n\n/**\n * Thrown when tool execution fails\n */\nexport class ToolExecutionError extends MCPError {\n constructor(toolName: string, reason: string, cause?: Error) {\n super(ErrorCodes.TOOL_EXECUTION_ERROR, `Tool '${toolName}' failed: ${reason}`, {\n tool: toolName,\n reason,\n ...(cause && { cause: cause.message }),\n })\n this.name = 'ToolExecutionError'\n }\n}\n\n/**\n * Thrown when a requested resource doesn't exist\n */\nexport class ResourceNotFoundError extends MCPError {\n constructor(resourceUri: string) {\n super(ErrorCodes.RESOURCE_NOT_FOUND, `Resource '${resourceUri}' not found`, {\n uri: resourceUri,\n })\n this.name = 'ResourceNotFoundError'\n }\n}\n\n/**\n * Thrown when authentication fails\n */\nexport class AuthenticationError extends MCPError {\n constructor(reason: string = 'Authentication required') {\n super(ErrorCodes.AUTHENTICATION_ERROR, reason)\n this.name = 'AuthenticationError'\n }\n}\n\n/**\n * Thrown when authorization fails (authenticated but not permitted)\n */\nexport class AuthorizationError extends MCPError {\n constructor(action: string, resource?: string) {\n const msg = resource\n ? `Not authorized to ${action} on '${resource}'`\n : `Not authorized to ${action}`\n super(ErrorCodes.AUTHORIZATION_ERROR, msg, {\n action,\n ...(resource && { resource }),\n })\n this.name = 'AuthorizationError'\n }\n}\n\n/**\n * Thrown when rate limits are exceeded\n */\nexport class RateLimitError extends MCPError {\n constructor(retryAfterMs?: number) {\n super(ErrorCodes.RATE_LIMIT_ERROR, 'Rate limit exceeded', {\n ...(retryAfterMs && { retryAfterMs }),\n })\n this.name = 'RateLimitError'\n }\n}\n\n/**\n * Thrown when an operation times out\n */\nexport class TimeoutError extends MCPError {\n constructor(operation: string, timeoutMs: number) {\n super(ErrorCodes.TIMEOUT_ERROR, `Operation '${operation}' timed out after ${timeoutMs}ms`, {\n operation,\n timeoutMs,\n })\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a required dependency is unavailable\n */\nexport class DependencyError extends MCPError {\n constructor(dependency: string, reason: string) {\n super(ErrorCodes.DEPENDENCY_ERROR, `Dependency '${dependency}' unavailable: ${reason}`, {\n dependency,\n reason,\n })\n this.name = 'DependencyError'\n }\n}\n\n/**\n * Thrown when server configuration is invalid\n */\nexport class ConfigurationError extends MCPError {\n constructor(setting: string, reason: string) {\n super(ErrorCodes.CONFIGURATION_ERROR, `Invalid configuration '${setting}': ${reason}`, {\n setting,\n reason,\n })\n this.name = 'ConfigurationError'\n }\n}\n\n/**\n * Thrown when payment is required to access a tool\n */\nexport class PaymentRequiredError extends MCPError {\n constructor(toolName: string, options?: { upgradeUrl?: string; priceId?: string }) {\n super(ErrorCodes.PAYMENT_REQUIRED, `Payment required to use '${toolName}'`, {\n tool: toolName,\n ...(options?.upgradeUrl && { upgradeUrl: options.upgradeUrl }),\n ...(options?.priceId && { priceId: options.priceId }),\n })\n this.name = 'PaymentRequiredError'\n }\n}\n\n/**\n * Thrown when user doesn't have enough credits\n */\nexport class InsufficientCreditsError extends MCPError {\n constructor(required: number, available: number, options?: { purchaseUrl?: string }) {\n super(ErrorCodes.INSUFFICIENT_CREDITS, `Insufficient credits: need ${required}, have ${available}`, {\n required,\n available,\n ...(options?.purchaseUrl && { purchaseUrl: options.purchaseUrl }),\n })\n this.name = 'InsufficientCreditsError'\n }\n}\n\n/**\n * Thrown when a subscription tier is required\n */\nexport class SubscriptionRequiredError extends MCPError {\n constructor(requiredTier: string, currentTier?: string, options?: { upgradeUrl?: string }) {\n const msg = currentTier \n ? `Subscription '${requiredTier}' required (current: '${currentTier}')`\n : `Subscription '${requiredTier}' required`\n super(ErrorCodes.SUBSCRIPTION_REQUIRED, msg, {\n requiredTier,\n ...(currentTier && { currentTier }),\n ...(options?.upgradeUrl && { upgradeUrl: options.upgradeUrl }),\n })\n this.name = 'SubscriptionRequiredError'\n }\n}\n","import { z, ZodError, type ZodSchema, type ZodTypeDef, type SafeParseReturnType } from 'zod'\nimport { ValidationError } from '../errors'\n\n// Re-export zod for convenience\nexport { z, ZodError, type ZodSchema }\nexport type { ZodTypeDef }\n\n/**\n * Options for input validation\n */\nexport interface ValidateOptions {\n /** Strip unknown keys from objects (default: true) */\n stripUnknown?: boolean\n /** Custom error formatter */\n formatError?: (error: ZodError) => string\n}\n\n/**\n * Validates input against a Zod schema\n * Throws ValidationError on failure with detailed field info\n */\nexport function validate<T>(\n schema: ZodSchema<T>,\n input: unknown,\n options: ValidateOptions = {}\n): T {\n const { stripUnknown = true } = options\n\n const result = (\n stripUnknown\n ? schema.safeParse(input)\n : schema instanceof z.ZodObject\n ? schema.strict().safeParse(input)\n : schema.safeParse(input)\n ) as SafeParseReturnType<unknown, T>\n\n if (!result.success) {\n const firstError = result.error.errors[0]\n const field = firstError.path.join('.') || 'input'\n const reason = firstError.message\n throw new ValidationError(field, reason, firstError.path.length > 0 \n ? getNestedValue(input, firstError.path) \n : input\n )\n }\n\n return result.data\n}\n\n/**\n * Creates a validated tool handler\n * Wraps your handler function with automatic input validation\n */\nexport function validateInput<TInput, TOutput>(\n schema: ZodSchema<TInput>,\n handler: (input: TInput) => TOutput | Promise<TOutput>,\n options: ValidateOptions = {}\n): (input: unknown) => Promise<TOutput> {\n return async (input: unknown) => {\n const validated = validate(schema, input, options)\n return handler(validated)\n }\n}\n\n\n/**\n * Helper to extract nested value from object by path\n */\nfunction getNestedValue(obj: unknown, path: (string | number)[]): unknown {\n let current = obj\n for (const key of path) {\n if (current === null || current === undefined) return undefined\n current = (current as Record<string | number, unknown>)[key]\n }\n return current\n}\n\n/**\n * Common schema patterns for MCP tools\n */\nexport const schemas = {\n /** Non-empty string */\n nonEmptyString: z.string().min(1, 'Cannot be empty'),\n \n /** Positive integer */\n positiveInt: z.number().int().positive(),\n \n /** Pagination limit (1-100, default 10) */\n limit: z.number().int().min(1).max(100).default(10),\n \n /** Pagination offset (>= 0, default 0) */\n offset: z.number().int().min(0).default(0),\n \n /** URL string */\n url: z.string().url(),\n \n /** Email string */\n email: z.string().email(),\n \n /** UUID string */\n uuid: z.string().uuid(),\n \n /** ISO date string */\n isoDate: z.string().datetime(),\n \n /** Boolean with string coercion ('true'/'false' -> boolean) */\n booleanish: z.union([\n z.boolean(),\n z.enum(['true', 'false']).transform(v => v === 'true'),\n ]),\n}\n\n/**\n * Type helper to infer schema type\n */\nexport type Infer<T extends ZodSchema> = z.infer<T>\n","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n timestamp?: string\n level: LogLevel\n service: string\n message: string\n [key: string]: unknown\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel\n /** Custom output function (default: console methods) */\n output?: (entry: LogEntry) => void\n /** Include timestamps (default: true) */\n timestamps?: boolean\n /** Pretty print JSON (default: false, use true for local dev) */\n pretty?: boolean\n}\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a structured logger for MCP servers\n */\nexport function createLogger(service: string, options: LoggerOptions = {}) {\n const {\n level: minLevel = 'info',\n timestamps = true,\n pretty = false,\n } = options\n\n const shouldLog = (level: LogLevel): boolean => {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel]\n }\n\n const formatEntry = (entry: LogEntry): string => {\n return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry)\n }\n\n const log = (level: LogLevel, message: string, data?: Record<string, unknown>) => {\n if (!shouldLog(level)) return\n\n const entry: LogEntry = {\n ...(timestamps && { timestamp: new Date().toISOString() }),\n level,\n service,\n message,\n ...data,\n }\n\n if (options.output) {\n options.output(entry)\n } else {\n const formatted = formatEntry(entry)\n switch (level) {\n case 'debug':\n console.debug(formatted)\n break\n case 'info':\n console.info(formatted)\n break\n case 'warn':\n console.warn(formatted)\n break\n case 'error':\n console.error(formatted)\n break\n }\n }\n\n return entry\n }\n\n return {\n debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),\n info: (message: string, data?: Record<string, unknown>) => log('info', message, data),\n warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),\n error: (message: string, data?: Record<string, unknown>) => log('error', message, data),\n \n /**\n * Create a child logger with additional context\n */\n child: (context: Record<string, unknown>) => {\n return createLogger(service, {\n ...options,\n output: (entry) => {\n const merged = { ...entry, ...context }\n if (options.output) {\n options.output(merged)\n } else {\n const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged)\n console[entry.level](formatted)\n }\n },\n })\n },\n }\n}\n\nexport type Logger = ReturnType<typeof createLogger>\n","export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '1.0.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n","import { MCPError, ToolExecutionError, TimeoutError } from '../errors'\nimport { createLogger, type Logger } from '../logger'\nimport { getTelemetry } from '../telemetry'\n\nexport interface HealthCheckInfo {\n name: string\n version: string\n description?: string\n uptime?: () => number\n checks?: Record<string, () => Promise<boolean> | boolean>\n}\n\nexport interface HealthCheckResponse {\n status: 'healthy' | 'degraded' | 'unhealthy'\n name: string\n version: string\n description?: string\n uptime?: number\n timestamp: string\n checks?: Record<string, boolean>\n}\n\n/**\n * Creates a standard health check response for MCP servers\n */\nexport function createHealthCheck(info: HealthCheckInfo) {\n return async (): Promise<HealthCheckResponse> => {\n const checks: Record<string, boolean> = {}\n let allHealthy = true\n\n if (info.checks) {\n for (const [name, check] of Object.entries(info.checks)) {\n try {\n checks[name] = await check()\n if (!checks[name]) allHealthy = false\n } catch {\n checks[name] = false\n allHealthy = false\n }\n }\n }\n\n return {\n status: allHealthy ? 'healthy' : 'degraded',\n name: info.name,\n version: info.version,\n ...(info.description && { description: info.description }),\n ...(info.uptime && { uptime: info.uptime() }),\n timestamp: new Date().toISOString(),\n ...(Object.keys(checks).length > 0 && { checks }),\n }\n }\n}\n\n\nexport interface WrapToolOptions {\n /** Tool name for logging and telemetry */\n name: string\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number\n /** Custom logger instance */\n logger?: Logger\n /** Enable telemetry reporting (default: true if telemetry initialized) */\n telemetry?: boolean\n}\n\nexport interface ToolContext {\n /** Unique ID for this tool call */\n callId: string\n /** Tool name */\n name: string\n /** Start time of execution */\n startTime: number\n /** Logger scoped to this call */\n log: Logger\n}\n\n/**\n * Wraps a tool handler with automatic error handling, logging, timeouts, and telemetry\n */\nexport function wrapTool<TInput, TOutput>(\n handler: (input: TInput, ctx: ToolContext) => TOutput | Promise<TOutput>,\n options: WrapToolOptions\n): (input: TInput) => Promise<TOutput> {\n const {\n name,\n timeout = 30000,\n telemetry: enableTelemetry = true,\n } = options\n\n const baseLogger = options.logger ?? createLogger(name)\n\n return async (input: TInput): Promise<TOutput> => {\n const callId = generateCallId()\n const startTime = Date.now()\n const log = baseLogger.child({ callId })\n\n const ctx: ToolContext = { callId, name, startTime, log }\n\n log.info('Tool invoked', { tool: name, input: sanitizeInput(input) })\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(name, timeout))\n }, timeout)\n })\n\n // Race handler against timeout\n const result = await Promise.race([\n Promise.resolve(handler(input, ctx)),\n timeoutPromise,\n ])\n\n const duration = Date.now() - startTime\n log.info('Tool completed', { tool: name, duration })\n\n // Report success to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, true)\n }\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n log.error('Tool failed', { \n tool: name, \n duration, \n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n })\n\n // Report failure to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, false, errorMessage)\n }\n\n // Re-throw MCPErrors as-is, wrap others\n if (error instanceof MCPError) {\n throw error\n }\n\n throw new ToolExecutionError(\n name,\n errorMessage,\n error instanceof Error ? error : undefined\n )\n }\n }\n}\n\n/**\n * Generates a unique call ID\n */\nfunction generateCallId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * Sanitizes input for logging (removes sensitive fields)\n */\nfunction sanitizeInput(input: unknown): unknown {\n if (typeof input !== 'object' || input === null) return input\n\n const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth', 'credential']\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (sensitiveKeys.some(k => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]'\n } else {\n sanitized[key] = value\n }\n }\n\n return sanitized\n}\n","import {\n PaymentRequiredError,\n InsufficientCreditsError,\n SubscriptionRequiredError,\n ConfigurationError,\n} from '../errors'\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface PaymentConfig {\n /** OpenConductor API key for billing */\n apiKey: string\n /** Base URL for billing API (default: https://api.openconductor.ai) */\n apiUrl?: string\n /** Default upgrade URL to show users */\n upgradeUrl?: string\n /** Enable test mode (skips actual billing) */\n testMode?: boolean\n}\n\nexport interface CreditRequirement {\n /** Number of credits to deduct per call */\n credits: number\n}\n\nexport interface SubscriptionRequirement {\n /** Required subscription tier (e.g., 'pro', 'enterprise') */\n tier: string\n /** Alternative tiers that also grant access */\n allowedTiers?: string[]\n}\n\nexport interface StripeRequirement {\n /** Stripe Price ID for per-call billing */\n priceId: string\n}\n\nexport type PaymentRequirement = \n | CreditRequirement \n | SubscriptionRequirement \n | StripeRequirement\n\nexport interface UserContext {\n /** User ID for billing lookup */\n userId: string\n /** Optional API key override */\n apiKey?: string\n}\n\nexport interface BillingStatus {\n /** Whether the user can proceed */\n allowed: boolean\n /** Current credit balance (if applicable) */\n credits?: number\n /** Current subscription tier (if applicable) */\n tier?: string\n /** Reason for denial (if not allowed) */\n reason?: string\n /** URL for upgrade/purchase */\n actionUrl?: string\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\nlet paymentConfig: PaymentConfig | null = null\n\n/**\n * Initialize payment/billing configuration\n * \n * @example\n * ```typescript\n * initPayment({\n * apiKey: process.env.OPENCONDUCTOR_API_KEY!,\n * upgradeUrl: 'https://myapp.com/upgrade'\n * })\n * ```\n */\nexport function initPayment(config: PaymentConfig): void {\n paymentConfig = {\n apiUrl: 'https://api.openconductor.ai',\n testMode: false,\n ...config,\n }\n}\n\n/**\n * Get current payment configuration\n */\nexport function getPaymentConfig(): PaymentConfig | null {\n return paymentConfig\n}\n\n// ============================================================================\n// Billing Client\n// ============================================================================\n\ninterface CheckBillingParams {\n userId: string\n requirement: PaymentRequirement\n toolName: string\n}\n\ninterface DeductCreditsParams {\n userId: string\n credits: number\n toolName: string\n callId?: string\n}\n\nasync function checkBilling(params: CheckBillingParams): Promise<BillingStatus> {\n const config = paymentConfig\n if (!config) {\n throw new ConfigurationError('payment', 'Payment not initialized. Call initPayment() first.')\n }\n\n // Test mode - always allow\n if (config.testMode) {\n return { allowed: true, credits: 9999, tier: 'test' }\n }\n\n try {\n const response = await fetch(`${config.apiUrl}/v1/billing/check`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`,\n },\n body: JSON.stringify({\n userId: params.userId,\n requirement: params.requirement,\n tool: params.toolName,\n }),\n })\n\n if (!response.ok) {\n // Non-2xx response - treat as billing check failed\n const errorBody = await response.text()\n console.error('[payment] Billing check failed:', response.status, errorBody)\n return {\n allowed: false,\n reason: 'Billing service unavailable',\n actionUrl: config.upgradeUrl,\n }\n }\n\n return await response.json() as BillingStatus\n } catch (error) {\n // Network error - fail open or closed based on config\n console.error('[payment] Billing check error:', error)\n return {\n allowed: false,\n reason: 'Unable to verify billing status',\n actionUrl: config.upgradeUrl,\n }\n }\n}\n\nasync function deductCredits(params: DeductCreditsParams): Promise<boolean> {\n const config = paymentConfig\n if (!config) return false\n\n // Test mode - don't actually deduct\n if (config.testMode) return true\n\n try {\n const response = await fetch(`${config.apiUrl}/v1/billing/deduct`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`,\n },\n body: JSON.stringify({\n userId: params.userId,\n credits: params.credits,\n tool: params.toolName,\n callId: params.callId,\n }),\n })\n\n return response.ok\n } catch (error) {\n console.error('[payment] Credit deduction error:', error)\n return false\n }\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nfunction isCreditRequirement(req: PaymentRequirement): req is CreditRequirement {\n return 'credits' in req && typeof req.credits === 'number'\n}\n\nfunction isSubscriptionRequirement(req: PaymentRequirement): req is SubscriptionRequirement {\n return 'tier' in req && typeof req.tier === 'string'\n}\n\nfunction isStripeRequirement(req: PaymentRequirement): req is StripeRequirement {\n return 'priceId' in req && typeof req.priceId === 'string'\n}\n\n// ============================================================================\n// Main Middleware\n// ============================================================================\n\nexport interface RequirePaymentOptions {\n /** Tool name for billing records */\n toolName?: string\n /** Function to extract user ID from input */\n getUserId?: (input: unknown) => string | undefined\n /** Custom error handler */\n onPaymentError?: (error: Error) => void\n}\n\n/**\n * One-line payment middleware for MCP tools\n * \n * @example Credits-based billing\n * ```typescript\n * const paidTool = requirePayment({ credits: 10 })(myHandler)\n * ```\n * \n * @example Subscription tier requirement\n * ```typescript\n * const premiumTool = requirePayment({ tier: 'pro' })(myHandler)\n * ```\n * \n * @example With wrapTool\n * ```typescript\n * const safePaidTool = wrapTool(\n * requirePayment({ credits: 5 })(myHandler),\n * { name: 'premium-analysis' }\n * )\n * ```\n */\nexport function requirePayment<TInput extends { userId?: string }, TOutput>(\n requirement: PaymentRequirement,\n options: RequirePaymentOptions = {}\n) {\n return (\n handler: (input: TInput) => TOutput | Promise<TOutput>\n ): ((input: TInput) => Promise<TOutput>) => {\n \n const { toolName = 'unknown', getUserId } = options\n\n return async (input: TInput): Promise<TOutput> => {\n // Extract user ID\n const userId = getUserId?.(input) ?? input.userId\n \n if (!userId) {\n throw new PaymentRequiredError(toolName, {\n upgradeUrl: paymentConfig?.upgradeUrl,\n })\n }\n\n // Check billing status\n const status = await checkBilling({\n userId,\n requirement,\n toolName,\n })\n\n if (!status.allowed) {\n // Throw appropriate error based on requirement type\n if (isCreditRequirement(requirement)) {\n throw new InsufficientCreditsError(\n requirement.credits,\n status.credits ?? 0,\n { purchaseUrl: status.actionUrl }\n )\n }\n\n if (isSubscriptionRequirement(requirement)) {\n throw new SubscriptionRequiredError(\n requirement.tier,\n status.tier,\n { upgradeUrl: status.actionUrl }\n )\n }\n\n // Generic payment required\n throw new PaymentRequiredError(toolName, {\n upgradeUrl: status.actionUrl,\n ...(isStripeRequirement(requirement) && { priceId: requirement.priceId }),\n })\n }\n\n // Execute the handler\n const result = await handler(input)\n\n // Deduct credits after successful execution (if credit-based)\n if (isCreditRequirement(requirement)) {\n await deductCredits({\n userId,\n credits: requirement.credits,\n toolName,\n })\n }\n\n return result\n }\n }\n}\n\n// ============================================================================\n// Convenience Functions\n// ============================================================================\n\n/**\n * Create a paid tool with built-in payment verification\n * \n * @example\n * ```typescript\n * const analyzeData = createPaidTool({\n * name: 'analyze-data',\n * payment: { credits: 10 },\n * handler: async (input) => {\n * // Your tool logic\n * return result\n * }\n * })\n * ```\n */\nexport function createPaidTool<TInput extends { userId?: string }, TOutput>(config: {\n name: string\n payment: PaymentRequirement\n handler: (input: TInput) => TOutput | Promise<TOutput>\n getUserId?: (input: TInput) => string | undefined\n}): (input: TInput) => Promise<TOutput> {\n return requirePayment<TInput, TOutput>(config.payment, {\n toolName: config.name,\n getUserId: config.getUserId as (input: unknown) => string | undefined,\n })(config.handler)\n}\n\n/**\n * Check if a user can access a paid feature without executing it\n * Useful for UI gating\n * \n * @example\n * ```typescript\n * const canAccess = await canUserAccess('user_123', { credits: 10 }, 'premium-tool')\n * if (!canAccess.allowed) {\n * showUpgradePrompt(canAccess.actionUrl)\n * }\n * ```\n */\nexport async function canUserAccess(\n userId: string,\n requirement: PaymentRequirement,\n toolName: string = 'check'\n): Promise<BillingStatus> {\n return checkBilling({ userId, requirement, toolName })\n}\n\n/**\n * Get user's current billing status\n */\nexport async function getUserBillingStatus(userId: string): Promise<{\n credits: number\n tier: string\n active: boolean\n} | null> {\n const config = paymentConfig\n if (!config) return null\n\n if (config.testMode) {\n return { credits: 9999, tier: 'test', active: true }\n }\n\n try {\n const response = await fetch(`${config.apiUrl}/v1/billing/status/${userId}`, {\n headers: {\n 'Authorization': `Bearer ${config.apiKey}`,\n },\n })\n\n if (!response.ok) return null\n return await response.json()\n } catch {\n return null\n }\n}\n"]}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
interface PaymentConfig {
|
|
2
|
+
/** OpenConductor API key for billing */
|
|
3
|
+
apiKey: string;
|
|
4
|
+
/** Base URL for billing API (default: https://api.openconductor.ai) */
|
|
5
|
+
apiUrl?: string;
|
|
6
|
+
/** Default upgrade URL to show users */
|
|
7
|
+
upgradeUrl?: string;
|
|
8
|
+
/** Enable test mode (skips actual billing) */
|
|
9
|
+
testMode?: boolean;
|
|
10
|
+
}
|
|
11
|
+
interface CreditRequirement {
|
|
12
|
+
/** Number of credits to deduct per call */
|
|
13
|
+
credits: number;
|
|
14
|
+
}
|
|
15
|
+
interface SubscriptionRequirement {
|
|
16
|
+
/** Required subscription tier (e.g., 'pro', 'enterprise') */
|
|
17
|
+
tier: string;
|
|
18
|
+
/** Alternative tiers that also grant access */
|
|
19
|
+
allowedTiers?: string[];
|
|
20
|
+
}
|
|
21
|
+
interface StripeRequirement {
|
|
22
|
+
/** Stripe Price ID for per-call billing */
|
|
23
|
+
priceId: string;
|
|
24
|
+
}
|
|
25
|
+
type PaymentRequirement = CreditRequirement | SubscriptionRequirement | StripeRequirement;
|
|
26
|
+
interface UserContext {
|
|
27
|
+
/** User ID for billing lookup */
|
|
28
|
+
userId: string;
|
|
29
|
+
/** Optional API key override */
|
|
30
|
+
apiKey?: string;
|
|
31
|
+
}
|
|
32
|
+
interface BillingStatus {
|
|
33
|
+
/** Whether the user can proceed */
|
|
34
|
+
allowed: boolean;
|
|
35
|
+
/** Current credit balance (if applicable) */
|
|
36
|
+
credits?: number;
|
|
37
|
+
/** Current subscription tier (if applicable) */
|
|
38
|
+
tier?: string;
|
|
39
|
+
/** Reason for denial (if not allowed) */
|
|
40
|
+
reason?: string;
|
|
41
|
+
/** URL for upgrade/purchase */
|
|
42
|
+
actionUrl?: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Initialize payment/billing configuration
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* initPayment({
|
|
50
|
+
* apiKey: process.env.OPENCONDUCTOR_API_KEY!,
|
|
51
|
+
* upgradeUrl: 'https://myapp.com/upgrade'
|
|
52
|
+
* })
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
declare function initPayment(config: PaymentConfig): void;
|
|
56
|
+
/**
|
|
57
|
+
* Get current payment configuration
|
|
58
|
+
*/
|
|
59
|
+
declare function getPaymentConfig(): PaymentConfig | null;
|
|
60
|
+
interface RequirePaymentOptions {
|
|
61
|
+
/** Tool name for billing records */
|
|
62
|
+
toolName?: string;
|
|
63
|
+
/** Function to extract user ID from input */
|
|
64
|
+
getUserId?: (input: unknown) => string | undefined;
|
|
65
|
+
/** Custom error handler */
|
|
66
|
+
onPaymentError?: (error: Error) => void;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* One-line payment middleware for MCP tools
|
|
70
|
+
*
|
|
71
|
+
* @example Credits-based billing
|
|
72
|
+
* ```typescript
|
|
73
|
+
* const paidTool = requirePayment({ credits: 10 })(myHandler)
|
|
74
|
+
* ```
|
|
75
|
+
*
|
|
76
|
+
* @example Subscription tier requirement
|
|
77
|
+
* ```typescript
|
|
78
|
+
* const premiumTool = requirePayment({ tier: 'pro' })(myHandler)
|
|
79
|
+
* ```
|
|
80
|
+
*
|
|
81
|
+
* @example With wrapTool
|
|
82
|
+
* ```typescript
|
|
83
|
+
* const safePaidTool = wrapTool(
|
|
84
|
+
* requirePayment({ credits: 5 })(myHandler),
|
|
85
|
+
* { name: 'premium-analysis' }
|
|
86
|
+
* )
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
declare function requirePayment<TInput extends {
|
|
90
|
+
userId?: string;
|
|
91
|
+
}, TOutput>(requirement: PaymentRequirement, options?: RequirePaymentOptions): (handler: (input: TInput) => TOutput | Promise<TOutput>) => ((input: TInput) => Promise<TOutput>);
|
|
92
|
+
/**
|
|
93
|
+
* Create a paid tool with built-in payment verification
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```typescript
|
|
97
|
+
* const analyzeData = createPaidTool({
|
|
98
|
+
* name: 'analyze-data',
|
|
99
|
+
* payment: { credits: 10 },
|
|
100
|
+
* handler: async (input) => {
|
|
101
|
+
* // Your tool logic
|
|
102
|
+
* return result
|
|
103
|
+
* }
|
|
104
|
+
* })
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
declare function createPaidTool<TInput extends {
|
|
108
|
+
userId?: string;
|
|
109
|
+
}, TOutput>(config: {
|
|
110
|
+
name: string;
|
|
111
|
+
payment: PaymentRequirement;
|
|
112
|
+
handler: (input: TInput) => TOutput | Promise<TOutput>;
|
|
113
|
+
getUserId?: (input: TInput) => string | undefined;
|
|
114
|
+
}): (input: TInput) => Promise<TOutput>;
|
|
115
|
+
/**
|
|
116
|
+
* Check if a user can access a paid feature without executing it
|
|
117
|
+
* Useful for UI gating
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
120
|
+
* ```typescript
|
|
121
|
+
* const canAccess = await canUserAccess('user_123', { credits: 10 }, 'premium-tool')
|
|
122
|
+
* if (!canAccess.allowed) {
|
|
123
|
+
* showUpgradePrompt(canAccess.actionUrl)
|
|
124
|
+
* }
|
|
125
|
+
* ```
|
|
126
|
+
*/
|
|
127
|
+
declare function canUserAccess(userId: string, requirement: PaymentRequirement, toolName?: string): Promise<BillingStatus>;
|
|
128
|
+
/**
|
|
129
|
+
* Get user's current billing status
|
|
130
|
+
*/
|
|
131
|
+
declare function getUserBillingStatus(userId: string): Promise<{
|
|
132
|
+
credits: number;
|
|
133
|
+
tier: string;
|
|
134
|
+
active: boolean;
|
|
135
|
+
} | null>;
|
|
136
|
+
|
|
137
|
+
export { type BillingStatus, type CreditRequirement, type PaymentConfig, type PaymentRequirement, type RequirePaymentOptions, type StripeRequirement, type SubscriptionRequirement, type UserContext, canUserAccess, createPaidTool, getPaymentConfig, getUserBillingStatus, initPayment, requirePayment };
|