@mcpmesh/sdk 0.8.0-beta.1

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 (145) hide show
  1. package/dist/__tests__/claude-handler.test.d.ts +7 -0
  2. package/dist/__tests__/claude-handler.test.d.ts.map +1 -0
  3. package/dist/__tests__/claude-handler.test.js +455 -0
  4. package/dist/__tests__/claude-handler.test.js.map +1 -0
  5. package/dist/__tests__/config.test.d.ts +7 -0
  6. package/dist/__tests__/config.test.d.ts.map +1 -0
  7. package/dist/__tests__/config.test.js +156 -0
  8. package/dist/__tests__/config.test.js.map +1 -0
  9. package/dist/__tests__/errors.test.d.ts +7 -0
  10. package/dist/__tests__/errors.test.d.ts.map +1 -0
  11. package/dist/__tests__/errors.test.js +170 -0
  12. package/dist/__tests__/errors.test.js.map +1 -0
  13. package/dist/__tests__/generic-handler.test.d.ts +7 -0
  14. package/dist/__tests__/generic-handler.test.d.ts.map +1 -0
  15. package/dist/__tests__/generic-handler.test.js +243 -0
  16. package/dist/__tests__/generic-handler.test.js.map +1 -0
  17. package/dist/__tests__/llm-provider.test.d.ts +7 -0
  18. package/dist/__tests__/llm-provider.test.d.ts.map +1 -0
  19. package/dist/__tests__/llm-provider.test.js +217 -0
  20. package/dist/__tests__/llm-provider.test.js.map +1 -0
  21. package/dist/__tests__/openai-handler.test.d.ts +7 -0
  22. package/dist/__tests__/openai-handler.test.d.ts.map +1 -0
  23. package/dist/__tests__/openai-handler.test.js +359 -0
  24. package/dist/__tests__/openai-handler.test.js.map +1 -0
  25. package/dist/__tests__/provider-handler-registry.test.d.ts +9 -0
  26. package/dist/__tests__/provider-handler-registry.test.d.ts.map +1 -0
  27. package/dist/__tests__/provider-handler-registry.test.js +187 -0
  28. package/dist/__tests__/provider-handler-registry.test.js.map +1 -0
  29. package/dist/__tests__/response-parser.test.d.ts +7 -0
  30. package/dist/__tests__/response-parser.test.d.ts.map +1 -0
  31. package/dist/__tests__/response-parser.test.js +360 -0
  32. package/dist/__tests__/response-parser.test.js.map +1 -0
  33. package/dist/__tests__/route.test.d.ts +7 -0
  34. package/dist/__tests__/route.test.d.ts.map +1 -0
  35. package/dist/__tests__/route.test.js +281 -0
  36. package/dist/__tests__/route.test.js.map +1 -0
  37. package/dist/__tests__/sse.test.d.ts +7 -0
  38. package/dist/__tests__/sse.test.d.ts.map +1 -0
  39. package/dist/__tests__/sse.test.js +172 -0
  40. package/dist/__tests__/sse.test.js.map +1 -0
  41. package/dist/__tests__/template.test.d.ts +7 -0
  42. package/dist/__tests__/template.test.d.ts.map +1 -0
  43. package/dist/__tests__/template.test.js +176 -0
  44. package/dist/__tests__/template.test.js.map +1 -0
  45. package/dist/__tests__/tracing.test.d.ts +7 -0
  46. package/dist/__tests__/tracing.test.d.ts.map +1 -0
  47. package/dist/__tests__/tracing.test.js +264 -0
  48. package/dist/__tests__/tracing.test.js.map +1 -0
  49. package/dist/agent.d.ts +165 -0
  50. package/dist/agent.d.ts.map +1 -0
  51. package/dist/agent.js +626 -0
  52. package/dist/agent.js.map +1 -0
  53. package/dist/api-runtime.d.ts +166 -0
  54. package/dist/api-runtime.d.ts.map +1 -0
  55. package/dist/api-runtime.js +459 -0
  56. package/dist/api-runtime.js.map +1 -0
  57. package/dist/config.d.ts +31 -0
  58. package/dist/config.d.ts.map +1 -0
  59. package/dist/config.js +60 -0
  60. package/dist/config.js.map +1 -0
  61. package/dist/debug.d.ts +47 -0
  62. package/dist/debug.d.ts.map +1 -0
  63. package/dist/debug.js +86 -0
  64. package/dist/debug.js.map +1 -0
  65. package/dist/errors.d.ts +99 -0
  66. package/dist/errors.d.ts.map +1 -0
  67. package/dist/errors.js +110 -0
  68. package/dist/errors.js.map +1 -0
  69. package/dist/express.d.ts +146 -0
  70. package/dist/express.d.ts.map +1 -0
  71. package/dist/express.js +371 -0
  72. package/dist/express.js.map +1 -0
  73. package/dist/index.d.ts +96 -0
  74. package/dist/index.d.ts.map +1 -0
  75. package/dist/index.js +107 -0
  76. package/dist/index.js.map +1 -0
  77. package/dist/llm-agent.d.ts +193 -0
  78. package/dist/llm-agent.d.ts.map +1 -0
  79. package/dist/llm-agent.js +634 -0
  80. package/dist/llm-agent.js.map +1 -0
  81. package/dist/llm-provider.d.ts +323 -0
  82. package/dist/llm-provider.d.ts.map +1 -0
  83. package/dist/llm-provider.js +446 -0
  84. package/dist/llm-provider.js.map +1 -0
  85. package/dist/llm.d.ts +194 -0
  86. package/dist/llm.d.ts.map +1 -0
  87. package/dist/llm.js +304 -0
  88. package/dist/llm.js.map +1 -0
  89. package/dist/provider-handlers/claude-handler.d.ts +98 -0
  90. package/dist/provider-handlers/claude-handler.d.ts.map +1 -0
  91. package/dist/provider-handlers/claude-handler.js +268 -0
  92. package/dist/provider-handlers/claude-handler.js.map +1 -0
  93. package/dist/provider-handlers/gemini-handler.d.ts +82 -0
  94. package/dist/provider-handlers/gemini-handler.d.ts.map +1 -0
  95. package/dist/provider-handlers/gemini-handler.js +152 -0
  96. package/dist/provider-handlers/gemini-handler.js.map +1 -0
  97. package/dist/provider-handlers/generic-handler.d.ts +78 -0
  98. package/dist/provider-handlers/generic-handler.d.ts.map +1 -0
  99. package/dist/provider-handlers/generic-handler.js +152 -0
  100. package/dist/provider-handlers/generic-handler.js.map +1 -0
  101. package/dist/provider-handlers/index.d.ts +29 -0
  102. package/dist/provider-handlers/index.d.ts.map +1 -0
  103. package/dist/provider-handlers/index.js +32 -0
  104. package/dist/provider-handlers/index.js.map +1 -0
  105. package/dist/provider-handlers/openai-handler.d.ts +86 -0
  106. package/dist/provider-handlers/openai-handler.d.ts.map +1 -0
  107. package/dist/provider-handlers/openai-handler.js +160 -0
  108. package/dist/provider-handlers/openai-handler.js.map +1 -0
  109. package/dist/provider-handlers/provider-handler-registry.d.ts +124 -0
  110. package/dist/provider-handlers/provider-handler-registry.d.ts.map +1 -0
  111. package/dist/provider-handlers/provider-handler-registry.js +180 -0
  112. package/dist/provider-handlers/provider-handler-registry.js.map +1 -0
  113. package/dist/provider-handlers/provider-handler.d.ts +245 -0
  114. package/dist/provider-handlers/provider-handler.d.ts.map +1 -0
  115. package/dist/provider-handlers/provider-handler.js +238 -0
  116. package/dist/provider-handlers/provider-handler.js.map +1 -0
  117. package/dist/proxy.d.ts +44 -0
  118. package/dist/proxy.d.ts.map +1 -0
  119. package/dist/proxy.js +324 -0
  120. package/dist/proxy.js.map +1 -0
  121. package/dist/response-parser.d.ts +103 -0
  122. package/dist/response-parser.d.ts.map +1 -0
  123. package/dist/response-parser.js +232 -0
  124. package/dist/response-parser.js.map +1 -0
  125. package/dist/route.d.ts +185 -0
  126. package/dist/route.d.ts.map +1 -0
  127. package/dist/route.js +310 -0
  128. package/dist/route.js.map +1 -0
  129. package/dist/sse.d.ts +45 -0
  130. package/dist/sse.d.ts.map +1 -0
  131. package/dist/sse.js +77 -0
  132. package/dist/sse.js.map +1 -0
  133. package/dist/template.d.ts +86 -0
  134. package/dist/template.d.ts.map +1 -0
  135. package/dist/template.js +206 -0
  136. package/dist/template.js.map +1 -0
  137. package/dist/tracing.d.ts +88 -0
  138. package/dist/tracing.d.ts.map +1 -0
  139. package/dist/tracing.js +193 -0
  140. package/dist/tracing.js.map +1 -0
  141. package/dist/types.d.ts +618 -0
  142. package/dist/types.d.ts.map +1 -0
  143. package/dist/types.js +5 -0
  144. package/dist/types.js.map +1 -0
  145. package/package.json +68 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response-parser.js","sourceRoot":"","sources":["../src/response-parser.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAGH,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,wCAAwC;AACxC,OAAO,EAAE,kBAAkB,EAAE,CAAC;AAE9B;;;;;;;GAOG;AACH,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,6DAA6D;IAC7D,MAAM,cAAc,GAAG,OAA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,GAAG,IAAI,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;IACnC,CAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC"}
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Express route handler with mesh dependency injection.
3
+ *
4
+ * Provides `mesh.route()` for injecting mesh dependencies into Express routes.
5
+ * Similar to Python's `@mesh.route` decorator for FastAPI.
6
+ *
7
+ * When `mesh.route()` is first called, the API runtime automatically schedules
8
+ * itself to start via `process.nextTick()`. This allows all routes to be
9
+ * registered before connecting to the mesh.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import express from "express";
14
+ * import { mesh } from "@mcpmesh/sdk";
15
+ *
16
+ * const app = express();
17
+ * app.use(express.json());
18
+ *
19
+ * // mesh.route() triggers auto-init - no meshExpress() or start() needed!
20
+ * app.post("/compute", mesh.route(
21
+ * [{ capability: "calculator" }],
22
+ * async (req, res, { calculator }) => {
23
+ * const result = await calculator({ a: req.body.a, b: req.body.b });
24
+ * res.json({ result });
25
+ * }
26
+ * ));
27
+ *
28
+ * app.listen(3000);
29
+ * ```
30
+ */
31
+ import type { Request, Response, NextFunction, RequestHandler } from "express";
32
+ import type { DependencySpec, McpMeshAgent, DependencyKwargs } from "./types.js";
33
+ /**
34
+ * Dependencies object passed to route handlers.
35
+ * Keys are capability names, values are proxy instances (or null if unavailable).
36
+ */
37
+ export type RouteDependencies = Record<string, McpMeshAgent | null>;
38
+ /**
39
+ * Route handler function with dependency injection.
40
+ *
41
+ * @param req - Express request object
42
+ * @param res - Express response object
43
+ * @param deps - Resolved dependencies as an object (keys are capability names)
44
+ */
45
+ export type MeshRouteHandler = (req: Request, res: Response, deps: RouteDependencies) => void | Promise<void>;
46
+ /**
47
+ * Extended route handler with next function for middleware chaining.
48
+ */
49
+ export type MeshRouteHandlerWithNext = (req: Request, res: Response, deps: RouteDependencies, next: NextFunction) => void | Promise<void>;
50
+ /**
51
+ * Configuration for a mesh route.
52
+ */
53
+ export interface MeshRouteConfig {
54
+ /** Dependencies to inject */
55
+ dependencies: DependencySpec[];
56
+ /** Per-dependency configuration (indexed by position) */
57
+ dependencyKwargs?: DependencyKwargs[];
58
+ }
59
+ /**
60
+ * Internal route metadata stored in RouteRegistry.
61
+ */
62
+ export interface RouteMetadata {
63
+ /** Route identifier (METHOD:path) */
64
+ routeId: string;
65
+ /** HTTP method */
66
+ method: string;
67
+ /** Route path pattern */
68
+ path: string;
69
+ /** Normalized dependencies */
70
+ dependencies: Array<{
71
+ capability: string;
72
+ tags: string[];
73
+ version?: string;
74
+ }>;
75
+ /** Per-dependency kwargs */
76
+ dependencyKwargs?: DependencyKwargs[];
77
+ }
78
+ /**
79
+ * Global registry for mesh routes.
80
+ * Tracks all routes created with mesh.route() for dependency resolution.
81
+ */
82
+ export declare class RouteRegistry {
83
+ private static instance;
84
+ private routes;
85
+ private resolvedDeps;
86
+ private routeIdMapping;
87
+ private routeCounter;
88
+ private constructor();
89
+ static getInstance(): RouteRegistry;
90
+ /**
91
+ * Reset the registry (mainly for testing).
92
+ */
93
+ static reset(): void;
94
+ /**
95
+ * Register a route with its dependencies.
96
+ * Returns a unique route ID for dependency resolution.
97
+ */
98
+ registerRoute(method: string, path: string, dependencies: DependencySpec[], dependencyKwargs?: DependencyKwargs[]): string;
99
+ /**
100
+ * Get all registered routes.
101
+ */
102
+ getRoutes(): RouteMetadata[];
103
+ /**
104
+ * Get a route by ID.
105
+ * Handles lookup with old route IDs that have been remapped after introspection.
106
+ */
107
+ getRoute(routeId: string): RouteMetadata | undefined;
108
+ /**
109
+ * Resolve a route ID to its current ID (after any remapping).
110
+ */
111
+ resolveRouteId(routeId: string): string;
112
+ /**
113
+ * Update resolved dependency for a route.
114
+ * Handles old route IDs that have been remapped after introspection.
115
+ */
116
+ setDependency(routeId: string, depIndex: number, proxy: McpMeshAgent): void;
117
+ /**
118
+ * Remove resolved dependency for a route.
119
+ * Handles old route IDs that have been remapped after introspection.
120
+ */
121
+ removeDependency(routeId: string, depIndex: number): void;
122
+ /**
123
+ * Get resolved dependency for a route.
124
+ * Handles old route IDs that have been remapped after introspection.
125
+ */
126
+ getDependency(routeId: string, depIndex: number): McpMeshAgent | null;
127
+ /**
128
+ * Get all resolved dependencies for a route as an object.
129
+ * Keys are capability names for easy destructuring in handlers.
130
+ * Handles remapped route IDs (e.g., route_0_UNKNOWN:UNKNOWN -> GET:/time).
131
+ */
132
+ getDependenciesForRoute(routeId: string): RouteDependencies;
133
+ /**
134
+ * Clear all resolved dependencies (e.g., on registry disconnect).
135
+ */
136
+ clearAllDependencies(): void;
137
+ /**
138
+ * Update route metadata with proper method and path.
139
+ * Called after Express route introspection.
140
+ */
141
+ updateRouteInfo(routeId: string, method: string, path: string): void;
142
+ }
143
+ /**
144
+ * Reset auto-detection flag (for testing).
145
+ */
146
+ export declare function resetAutoDetection(): void;
147
+ /**
148
+ * Create an Express middleware that injects mesh dependencies.
149
+ *
150
+ * @param dependencies - Array of dependency specifications
151
+ * @param handler - Route handler receiving (req, res, deps)
152
+ * @returns Express middleware
153
+ *
154
+ * @example
155
+ * ```typescript
156
+ * app.post("/compute", mesh.route(
157
+ * [{ capability: "calculator" }],
158
+ * async (req, res, { calculator }) => {
159
+ * if (!calculator) {
160
+ * return res.status(503).json({ error: "Calculator service unavailable" });
161
+ * }
162
+ * const result = await calculator({ a: req.body.a, b: req.body.b });
163
+ * res.json({ result });
164
+ * }
165
+ * ));
166
+ * ```
167
+ */
168
+ export declare function route(dependencies: DependencySpec[], handler: MeshRouteHandler | MeshRouteHandlerWithNext, options?: {
169
+ dependencyKwargs?: DependencyKwargs[];
170
+ }): RequestHandler;
171
+ /**
172
+ * Alternative API: route with config object.
173
+ *
174
+ * @example
175
+ * ```typescript
176
+ * app.post("/compute", mesh.routeWithConfig({
177
+ * dependencies: [{ capability: "calculator" }],
178
+ * dependencyKwargs: [{ timeout: 60 }],
179
+ * }, async (req, res, { calculator }) => {
180
+ * // ...
181
+ * }));
182
+ * ```
183
+ */
184
+ export declare function routeWithConfig(config: MeshRouteConfig, handler: MeshRouteHandler | MeshRouteHandlerWithNext): RequestHandler;
185
+ //# sourceMappingURL=route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../src/route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAC/E,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAUjF;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI,CAAC,CAAC;AAEpE;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAC7B,GAAG,EAAE,OAAO,EACZ,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,iBAAiB,KACpB,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE1B;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG,CACrC,GAAG,EAAE,OAAO,EACZ,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,iBAAiB,EACvB,IAAI,EAAE,YAAY,KACf,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE1B;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,6BAA6B;IAC7B,YAAY,EAAE,cAAc,EAAE,CAAC;IAC/B,yDAAyD;IACzD,gBAAgB,CAAC,EAAE,gBAAgB,EAAE,CAAC;CACvC;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,qCAAqC;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,kBAAkB;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,yBAAyB;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,8BAA8B;IAC9B,YAAY,EAAE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B,IAAI,IAAI;IAI5B;;;OAGG;IACH,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI;CA+BrE;AA+BD;;GAEG;AACH,wBAAgB,kBAAkB,IAAI,IAAI,CAEzC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,KAAK,CACnB,YAAY,EAAE,cAAc,EAAE,EAC9B,OAAO,EAAE,gBAAgB,GAAG,wBAAwB,EACpD,OAAO,CAAC,EAAE;IAAE,gBAAgB,CAAC,EAAE,gBAAgB,EAAE,CAAA;CAAE,GAClD,cAAc,CAoEhB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,eAAe,EACvB,OAAO,EAAE,gBAAgB,GAAG,wBAAwB,GACnD,cAAc,CAIhB"}
package/dist/route.js ADDED
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Express route handler with mesh dependency injection.
3
+ *
4
+ * Provides `mesh.route()` for injecting mesh dependencies into Express routes.
5
+ * Similar to Python's `@mesh.route` decorator for FastAPI.
6
+ *
7
+ * When `mesh.route()` is first called, the API runtime automatically schedules
8
+ * itself to start via `process.nextTick()`. This allows all routes to be
9
+ * registered before connecting to the mesh.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import express from "express";
14
+ * import { mesh } from "@mcpmesh/sdk";
15
+ *
16
+ * const app = express();
17
+ * app.use(express.json());
18
+ *
19
+ * // mesh.route() triggers auto-init - no meshExpress() or start() needed!
20
+ * app.post("/compute", mesh.route(
21
+ * [{ capability: "calculator" }],
22
+ * async (req, res, { calculator }) => {
23
+ * const result = await calculator({ a: req.body.a, b: req.body.b });
24
+ * res.json({ result });
25
+ * }
26
+ * ));
27
+ *
28
+ * app.listen(3000);
29
+ * ```
30
+ */
31
+ import { normalizeDependency } from "./proxy.js";
32
+ import { getApiRuntime, introspectExpressRoutes } from "./api-runtime.js";
33
+ /**
34
+ * Global flag to track if Express auto-detection has been performed.
35
+ * We only need to do this once on first request.
36
+ */
37
+ let expressAutoDetected = false;
38
+ /**
39
+ * Global registry for mesh routes.
40
+ * Tracks all routes created with mesh.route() for dependency resolution.
41
+ */
42
+ export class RouteRegistry {
43
+ static instance = null;
44
+ routes = new Map();
45
+ resolvedDeps = new Map();
46
+ routeIdMapping = new Map(); // old ID → new ID
47
+ routeCounter = 0;
48
+ constructor() { }
49
+ static getInstance() {
50
+ if (!RouteRegistry.instance) {
51
+ RouteRegistry.instance = new RouteRegistry();
52
+ }
53
+ return RouteRegistry.instance;
54
+ }
55
+ /**
56
+ * Reset the registry (mainly for testing).
57
+ */
58
+ static reset() {
59
+ RouteRegistry.instance = null;
60
+ }
61
+ /**
62
+ * Register a route with its dependencies.
63
+ * Returns a unique route ID for dependency resolution.
64
+ */
65
+ registerRoute(method, path, dependencies, dependencyKwargs) {
66
+ // Generate unique route ID
67
+ const routeId = `route_${this.routeCounter++}_${method}:${path}`;
68
+ const normalizedDeps = dependencies.map(normalizeDependency);
69
+ this.routes.set(routeId, {
70
+ routeId,
71
+ method,
72
+ path,
73
+ dependencies: normalizedDeps,
74
+ dependencyKwargs,
75
+ });
76
+ return routeId;
77
+ }
78
+ /**
79
+ * Get all registered routes.
80
+ */
81
+ getRoutes() {
82
+ return Array.from(this.routes.values());
83
+ }
84
+ /**
85
+ * Get a route by ID.
86
+ * Handles lookup with old route IDs that have been remapped after introspection.
87
+ */
88
+ getRoute(routeId) {
89
+ // Check if this is an old ID that's been remapped
90
+ const actualId = this.routeIdMapping.get(routeId) || routeId;
91
+ return this.routes.get(actualId);
92
+ }
93
+ /**
94
+ * Resolve a route ID to its current ID (after any remapping).
95
+ */
96
+ resolveRouteId(routeId) {
97
+ return this.routeIdMapping.get(routeId) || routeId;
98
+ }
99
+ /**
100
+ * Update resolved dependency for a route.
101
+ * Handles old route IDs that have been remapped after introspection.
102
+ */
103
+ setDependency(routeId, depIndex, proxy) {
104
+ // Resolve to current route ID in case this is an old ID from Rust core
105
+ const actualId = this.routeIdMapping.get(routeId) || routeId;
106
+ const depKey = `${actualId}:dep_${depIndex}`;
107
+ this.resolvedDeps.set(depKey, proxy);
108
+ }
109
+ /**
110
+ * Remove resolved dependency for a route.
111
+ * Handles old route IDs that have been remapped after introspection.
112
+ */
113
+ removeDependency(routeId, depIndex) {
114
+ // Resolve to current route ID in case this is an old ID from Rust core
115
+ const actualId = this.routeIdMapping.get(routeId) || routeId;
116
+ const depKey = `${actualId}:dep_${depIndex}`;
117
+ this.resolvedDeps.delete(depKey);
118
+ }
119
+ /**
120
+ * Get resolved dependency for a route.
121
+ * Handles old route IDs that have been remapped after introspection.
122
+ */
123
+ getDependency(routeId, depIndex) {
124
+ // Resolve to current route ID in case this is an old ID from Rust core
125
+ const actualId = this.routeIdMapping.get(routeId) || routeId;
126
+ const depKey = `${actualId}:dep_${depIndex}`;
127
+ return this.resolvedDeps.get(depKey) ?? null;
128
+ }
129
+ /**
130
+ * Get all resolved dependencies for a route as an object.
131
+ * Keys are capability names for easy destructuring in handlers.
132
+ * Handles remapped route IDs (e.g., route_0_UNKNOWN:UNKNOWN -> GET:/time).
133
+ */
134
+ getDependenciesForRoute(routeId) {
135
+ // Use getRoute to handle remapped IDs
136
+ const route = this.getRoute(routeId);
137
+ if (!route)
138
+ return {};
139
+ // Use the resolved route ID for dependency lookup
140
+ const resolvedId = route.routeId;
141
+ const deps = {};
142
+ route.dependencies.forEach((dep, idx) => {
143
+ deps[dep.capability] = this.getDependency(resolvedId, idx);
144
+ });
145
+ return deps;
146
+ }
147
+ /**
148
+ * Clear all resolved dependencies (e.g., on registry disconnect).
149
+ */
150
+ clearAllDependencies() {
151
+ this.resolvedDeps.clear();
152
+ }
153
+ /**
154
+ * Update route metadata with proper method and path.
155
+ * Called after Express route introspection.
156
+ */
157
+ updateRouteInfo(routeId, method, path) {
158
+ const route = this.routes.get(routeId);
159
+ if (route) {
160
+ // Create new route ID with proper method:path
161
+ const newRouteId = `${method}:${path}`;
162
+ // Store mapping for old→new ID (for dependency events from Rust core)
163
+ this.routeIdMapping.set(routeId, newRouteId);
164
+ // Update the route metadata
165
+ route.method = method;
166
+ route.path = path;
167
+ route.routeId = newRouteId;
168
+ // Re-register with new ID
169
+ this.routes.delete(routeId);
170
+ this.routes.set(newRouteId, route);
171
+ // Migrate any resolved dependencies to new key
172
+ for (let i = 0; i < route.dependencies.length; i++) {
173
+ const oldKey = `${routeId}:dep_${i}`;
174
+ const newKey = `${newRouteId}:dep_${i}`;
175
+ const dep = this.resolvedDeps.get(oldKey);
176
+ if (dep) {
177
+ this.resolvedDeps.set(newKey, dep);
178
+ this.resolvedDeps.delete(oldKey);
179
+ }
180
+ }
181
+ }
182
+ }
183
+ }
184
+ /**
185
+ * Perform auto-detection of Express app, port, and routes on first request.
186
+ * This eliminates the need for mesh.bind() - everything is detected automatically.
187
+ *
188
+ * @param req - Express request object (provides access to app and socket)
189
+ */
190
+ function performExpressAutoDetection(req) {
191
+ try {
192
+ // Extract port from the socket
193
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
194
+ const socket = req.socket || req.connection;
195
+ const port = socket?.localPort || 0;
196
+ // Get Express app from request
197
+ const app = req.app;
198
+ if (app) {
199
+ // Introspect routes to get proper METHOD:path names
200
+ const routeCount = introspectExpressRoutes(app);
201
+ // Update runtime with detected info
202
+ getApiRuntime().updateExpressInfo(port, routeCount);
203
+ }
204
+ }
205
+ catch (err) {
206
+ // Don't fail the request if auto-detection fails
207
+ console.warn("Express auto-detection failed:", err);
208
+ }
209
+ }
210
+ /**
211
+ * Reset auto-detection flag (for testing).
212
+ */
213
+ export function resetAutoDetection() {
214
+ expressAutoDetected = false;
215
+ }
216
+ /**
217
+ * Create an Express middleware that injects mesh dependencies.
218
+ *
219
+ * @param dependencies - Array of dependency specifications
220
+ * @param handler - Route handler receiving (req, res, deps)
221
+ * @returns Express middleware
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * app.post("/compute", mesh.route(
226
+ * [{ capability: "calculator" }],
227
+ * async (req, res, { calculator }) => {
228
+ * if (!calculator) {
229
+ * return res.status(503).json({ error: "Calculator service unavailable" });
230
+ * }
231
+ * const result = await calculator({ a: req.body.a, b: req.body.b });
232
+ * res.json({ result });
233
+ * }
234
+ * ));
235
+ * ```
236
+ */
237
+ export function route(dependencies, handler, options) {
238
+ const registry = RouteRegistry.getInstance();
239
+ // We don't know the method/path yet since this is called before app.get/post/etc
240
+ // So we'll register with placeholder and update when the middleware is called
241
+ // Use a ref object so introspection can update it and the middleware sees the change
242
+ const routeRef = {
243
+ id: registry.registerRoute("UNKNOWN", // Will be determined at runtime from req.method
244
+ "UNKNOWN", // Will be determined at runtime from req.path
245
+ dependencies, options?.dependencyKwargs),
246
+ };
247
+ // Trigger auto-init of API runtime on first route() call
248
+ // Uses process.nextTick() to wait until all routes are registered
249
+ if (dependencies.length > 0) {
250
+ getApiRuntime().scheduleStart();
251
+ }
252
+ // Store normalized deps for the handler
253
+ const normalizedDeps = dependencies.map(normalizeDependency);
254
+ // Return Express middleware
255
+ const middleware = async (req, res, next) => {
256
+ try {
257
+ // Auto-detect Express app, port, and routes on first request
258
+ // This eliminates the need for mesh.bind()
259
+ if (!expressAutoDetected) {
260
+ expressAutoDetected = true;
261
+ performExpressAutoDetection(req);
262
+ }
263
+ // Get resolved dependencies as object (use ref to get current ID after introspection)
264
+ const deps = registry.getDependenciesForRoute(routeRef.id);
265
+ // Also try to resolve by capability name if route-specific resolution isn't available yet
266
+ // This handles the case where dependencies were resolved before the route was registered
267
+ for (const dep of normalizedDeps) {
268
+ if (deps[dep.capability] === undefined) {
269
+ deps[dep.capability] = null;
270
+ }
271
+ }
272
+ // Call handler with dependencies
273
+ if (handler.length === 4) {
274
+ // Handler accepts next function
275
+ await handler(req, res, deps, next);
276
+ }
277
+ else {
278
+ await handler(req, res, deps);
279
+ }
280
+ }
281
+ catch (error) {
282
+ next(error);
283
+ }
284
+ };
285
+ // Attach metadata for introspection
286
+ // Use routeRef so introspection can update the ID and middleware sees the change
287
+ middleware._meshRouteId = routeRef.id;
288
+ middleware._meshRouteRef = routeRef;
289
+ middleware._meshDependencies = normalizedDeps;
290
+ return middleware;
291
+ }
292
+ /**
293
+ * Alternative API: route with config object.
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * app.post("/compute", mesh.routeWithConfig({
298
+ * dependencies: [{ capability: "calculator" }],
299
+ * dependencyKwargs: [{ timeout: 60 }],
300
+ * }, async (req, res, { calculator }) => {
301
+ * // ...
302
+ * }));
303
+ * ```
304
+ */
305
+ export function routeWithConfig(config, handler) {
306
+ return route(config.dependencies, handler, {
307
+ dependencyKwargs: config.dependencyKwargs,
308
+ });
309
+ }
310
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.js","sourceRoot":"","sources":["../src/route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAIH,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE1E;;;GAGG;AACH,IAAI,mBAAmB,GAAG,KAAK,CAAC;AA6DhC;;;GAGG;AACH,MAAM,OAAO,aAAa;IAChB,MAAM,CAAC,QAAQ,GAAyB,IAAI,CAAC;IAC7C,MAAM,GAA+B,IAAI,GAAG,EAAE,CAAC;IAC/C,YAAY,GAA8B,IAAI,GAAG,EAAE,CAAC;IACpD,cAAc,GAAwB,IAAI,GAAG,EAAE,CAAC,CAAC,kBAAkB;IACnE,YAAY,GAAG,CAAC,CAAC;IAEzB,gBAAuB,CAAC;IAExB,MAAM,CAAC,WAAW;QAChB,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC;YAC5B,aAAa,CAAC,QAAQ,GAAG,IAAI,aAAa,EAAE,CAAC;QAC/C,CAAC;QACD,OAAO,aAAa,CAAC,QAAQ,CAAC;IAChC,CAAC;IAED;;OAEG;I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CAAC;AACpB,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,eAAe,CAC7B,MAAuB,EACvB,OAAoD;IAEpD,OAAO,KAAK,CAAC,MAAM,CAAC,YAAY,EAAE,OAAO,EAAE;QACzC,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;KAC1C,CAAC,CAAC;AACL,CAAC"}
package/dist/sse.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * SSE (Server-Sent Events) parsing utilities for MCP responses.
3
+ *
4
+ * FastMCP stateless HTTP stream returns responses in SSE format:
5
+ * ```
6
+ * event: message
7
+ * data: {"jsonrpc":"2.0","id":123,"result":{...}}
8
+ * ```
9
+ *
10
+ * This module provides utilities to parse these responses.
11
+ */
12
+ /**
13
+ * Parse a response that may be in SSE format or plain JSON.
14
+ *
15
+ * @param responseText - Raw response text from HTTP request
16
+ * @returns Parsed JSON object
17
+ * @throws Error if no data found in SSE response or JSON parse fails
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * // SSE format
22
+ * const sse = "event: message\ndata: {\"result\":42}\n";
23
+ * const result = parseSSEResponse(sse);
24
+ * // => { result: 42 }
25
+ *
26
+ * // Plain JSON (passed through)
27
+ * const json = '{"result":42}';
28
+ * const result = parseSSEResponse(json);
29
+ * // => { result: 42 }
30
+ * ```
31
+ */
32
+ export declare function parseSSEResponse<T = unknown>(responseText: string): T;
33
+ /**
34
+ * Check if a response text is in SSE format.
35
+ */
36
+ export declare function isSSEResponse(responseText: string): boolean;
37
+ /**
38
+ * Extract all data payloads from an SSE stream.
39
+ * Useful when multiple events are expected.
40
+ *
41
+ * @param responseText - Raw SSE response text
42
+ * @returns Array of parsed JSON objects from each data line
43
+ */
44
+ export declare function parseSSEStream<T = unknown>(responseText: string): T[];
45
+ //# sourceMappingURL=sse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,GAAG,OAAO,EAAE,YAAY,EAAE,MAAM,GAAG,CAAC,CAsBrE;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAE3D;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,CAAC,GAAG,OAAO,EAAE,YAAY,EAAE,MAAM,GAAG,CAAC,EAAE,CAcrE"}
package/dist/sse.js ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * SSE (Server-Sent Events) parsing utilities for MCP responses.
3
+ *
4
+ * FastMCP stateless HTTP stream returns responses in SSE format:
5
+ * ```
6
+ * event: message
7
+ * data: {"jsonrpc":"2.0","id":123,"result":{...}}
8
+ * ```
9
+ *
10
+ * This module provides utilities to parse these responses.
11
+ */
12
+ /**
13
+ * Parse a response that may be in SSE format or plain JSON.
14
+ *
15
+ * @param responseText - Raw response text from HTTP request
16
+ * @returns Parsed JSON object
17
+ * @throws Error if no data found in SSE response or JSON parse fails
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * // SSE format
22
+ * const sse = "event: message\ndata: {\"result\":42}\n";
23
+ * const result = parseSSEResponse(sse);
24
+ * // => { result: 42 }
25
+ *
26
+ * // Plain JSON (passed through)
27
+ * const json = '{"result":42}';
28
+ * const result = parseSSEResponse(json);
29
+ * // => { result: 42 }
30
+ * ```
31
+ */
32
+ export function parseSSEResponse(responseText) {
33
+ // Check if it's SSE format (starts with "event:")
34
+ if (responseText.startsWith("event:")) {
35
+ const lines = responseText.split("\n");
36
+ let jsonData = "";
37
+ // Extract the last "data:" line (in case of multiple events)
38
+ for (const line of lines) {
39
+ if (line.startsWith("data: ")) {
40
+ jsonData = line.slice(6); // Remove "data: " prefix
41
+ }
42
+ }
43
+ if (!jsonData) {
44
+ throw new Error("No data found in SSE response");
45
+ }
46
+ return JSON.parse(jsonData);
47
+ }
48
+ // Plain JSON - parse directly
49
+ return JSON.parse(responseText);
50
+ }
51
+ /**
52
+ * Check if a response text is in SSE format.
53
+ */
54
+ export function isSSEResponse(responseText) {
55
+ return responseText.startsWith("event:");
56
+ }
57
+ /**
58
+ * Extract all data payloads from an SSE stream.
59
+ * Useful when multiple events are expected.
60
+ *
61
+ * @param responseText - Raw SSE response text
62
+ * @returns Array of parsed JSON objects from each data line
63
+ */
64
+ export function parseSSEStream(responseText) {
65
+ const results = [];
66
+ const lines = responseText.split("\n");
67
+ for (const line of lines) {
68
+ if (line.startsWith("data: ")) {
69
+ const jsonData = line.slice(6);
70
+ if (jsonData.trim()) {
71
+ results.push(JSON.parse(jsonData));
72
+ }
73
+ }
74
+ }
75
+ return results;
76
+ }
77
+ //# sourceMappingURL=sse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.js","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,gBAAgB,CAAc,YAAoB;IAChE,kDAAkD;IAClD,IAAI,YAAY,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QACtC,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACvC,IAAI,QAAQ,GAAG,EAAE,CAAC;QAElB,6DAA6D;QAC7D,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,IAAI,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;gBAC9B,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACrD,CAAC;QACH,CAAC;QAED,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;QACnD,CAAC;QAED,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAM,CAAC;IACnC,CAAC;I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