-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathsources-api.test.ts
More file actions
478 lines (431 loc) · 16.4 KB
/
Copy pathsources-api.test.ts
File metadata and controls
478 lines (431 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
// Cloud: the integration catalog's full CRUD surface plus the "registered
// integration becomes invokable tools" promise, for all three bring-your-own
// protocols (OpenAPI / MCP / GraphQL) — entirely over the wire through the
// typed client. Upstream APIs are real HTTP servers started inside the
// scenario on 127.0.0.1 (the dev server allows local-network egress), so an
// execution proves the whole chain: catalog row → connection → stamped tool →
// QuickJS execution → live upstream request.
//
// Ported from apps/cloud/src/api/sources-api.node.test.ts. Cross-user
// isolation of personal connections (alice/bob in one org) is NOT covered
// here: minting a second member of an existing org has no public API surface.
import { randomBytes } from "node:crypto";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { expect } from "@effect/vitest";
import { Effect } from "effect";
import { composePluginApi } from "@executor-js/api/server";
import { graphqlHttpPlugin } from "@executor-js/plugin-graphql/api";
import {
makeGreetingGraphqlSchema,
serveGraphqlTestServer,
} from "@executor-js/plugin-graphql/testing";
import { mcpHttpPlugin } from "@executor-js/plugin-mcp/api";
import { makeGreetingMcpServer, serveMcpServer } from "@executor-js/plugin-mcp/testing";
import { openApiHttpPlugin } from "@executor-js/plugin-openapi/api";
import { serveOpenApiEchoTestServer } from "@executor-js/plugin-openapi/testing";
import { AuthTemplateSlug, ConnectionName, IntegrationSlug } from "@executor-js/sdk/shared";
import { scenario } from "../src/scenario";
import { Api, Target } from "../src/services";
const api = composePluginApi([openApiHttpPlugin(), mcpHttpPlugin(), graphqlHttpPlugin()] as const);
/** Unique, JS-identifier-safe slug per run (tool addresses are dotted member
* expressions inside executed code, so no dashes). */
const newSlug = (prefix: string) =>
IntegrationSlug.make(`${prefix}_${randomBytes(4).toString("hex")}`);
const MAIN = ConnectionName.make("main");
const PERSONAL = ConnectionName.make("personal");
const API_KEY = AuthTemplateSlug.make("apiKey");
const NONE = AuthTemplateSlug.make("none");
/** Minimal OpenAPI 3 spec with a single GET /ping operation. */
const pingSpec = JSON.stringify({
openapi: "3.0.3",
info: { title: "Ping API", version: "1.0.0" },
paths: {
"/ping": {
get: {
operationId: "ping",
summary: "Return a pong",
tags: ["default"],
responses: { "200": { description: "pong" } },
},
},
},
});
/** Narrow an execution result to "completed", failing with the run's text. */
const completed = <R extends { status: string; text: string }>(
execution: R,
): Extract<R, { status: "completed" }> => {
if (execution.status !== "completed") {
throw new Error(`execution did not complete (status=${execution.status}): ${execution.text}`);
}
return execution as Extract<R, { status: "completed" }>;
};
scenario(
"Integrations · an OpenAPI spec round-trips the catalog: add, fetch, update, remove",
{},
Effect.gen(function* () {
const target = yield* Target;
const apiSurface = yield* Api;
const identity = yield* target.newIdentity();
const client = yield* apiSurface.client(api, identity);
const slug = newSlug("srcapi");
const added = yield* client.openapi.addSpec({
payload: {
spec: { kind: "blob", value: pingSpec },
slug,
baseUrl: "http://127.0.0.1:59999", // never contacted during registration
},
});
expect(added.slug, "the integration keeps the requested slug").toBe(slug);
expect(added.toolCount, "the single operation was extracted as a tool").toBe(1);
const listed = yield* client.integrations.list();
expect(
listed.map((i) => String(i.slug)),
"the new integration is in the catalog",
).toContain(slug);
const fetched = yield* client.openapi.getIntegration({ params: { slug } });
expect(fetched, "the stored integration is fetchable through the plugin route").toMatchObject({
slug,
kind: "openapi",
});
yield* client.integrations.update({
params: { slug },
payload: { description: "Renamed API" },
});
const updated = yield* client.integrations.get({ params: { slug } });
expect(updated?.description, "the description change round-trips").toBe("Renamed API");
yield* client.integrations.remove({ params: { slug } });
const after = yield* client.integrations.list();
expect(
after.map((i) => String(i.slug)),
"the removed integration drops off the catalog",
).not.toContain(slug);
}),
);
scenario(
"Integrations · previewSpec reports a spec's operations before anything is stored",
{},
Effect.gen(function* () {
const target = yield* Target;
const apiSurface = yield* Api;
const identity = yield* target.newIdentity();
const client = yield* apiSurface.client(api, identity);
const preview = yield* client.openapi.previewSpec({ payload: { spec: pingSpec } });
expect(preview.operationCount, "the preview counts the spec's operations").toBe(1);
expect(preview.operations, "the preview lists each operation's identity").toEqual([
expect.objectContaining({ operationId: "ping", method: "get", path: "/ping" }),
]);
}),
);
scenario(
"Integrations · a connected OpenAPI operation executes against the live upstream API",
{},
Effect.scoped(
Effect.gen(function* () {
const target = yield* Target;
const apiSurface = yield* Api;
// A real upstream HTTP API on 127.0.0.1, closed by the scope's finalizer.
const server = yield* serveOpenApiEchoTestServer();
const identity = yield* target.newIdentity();
const client = yield* apiSurface.client(api, identity);
const slug = newSlug("srcapi");
yield* client.openapi.addSpec({
payload: {
spec: { kind: "blob", value: server.specJson },
slug,
description: "Invocable upstream API",
baseUrl: server.baseUrl,
},
});
// A connection mints + persists the per-connection tools.
yield* client.connections.create({
payload: {
owner: "org",
name: MAIN,
integration: slug,
template: API_KEY,
value: "static-token",
},
});
const tools = yield* client.tools.list({ query: { integration: slug } });
const address = `tools.${slug}.org.main.echo.echoMessage`;
expect(
tools.map((tool) => String(tool.address)),
"the operation is stamped as a per-connection tool",
).toContain(address);
const execution = completed(
yield* client.executions.execute({
payload: {
code: [
`const result = await ${address}({ message: "hello", suffix: "world" });`,
"return result;",
].join("\n"),
},
}),
);
expect(execution.isError, "the execution succeeded").toBe(false);
// Payload-first: `data` IS the upstream body; transport facts (status,
// headers) ride in the optional `http` side channel.
expect(execution.structured, "the tool returned the upstream's echo").toMatchObject({
result: {
ok: true,
data: { message: "hello", suffix: "world", path: "/echo/hello" },
},
});
const requests = yield* server.requests;
expect(
requests.map((request) => request.path),
"the upstream API actually received the call",
).toContain("/echo/hello");
}),
),
);
scenario(
"Integrations · MCP addServer registers the catalog row without dialing the endpoint",
{},
Effect.gen(function* () {
const target = yield* Target;
const apiSurface = yield* Api;
const identity = yield* target.newIdentity();
const client = yield* apiSurface.client(api, identity);
const slug = newSlug("srcmcp");
// Discovery is deferred to connection time, so a dead endpoint still
// registers successfully and is fetchable afterwards.
const added = yield* client.mcp.addServer({
payload: {
transport: "remote",
name: "Broken MCP",
endpoint: "http://127.0.0.1:1/mcp",
remoteTransport: "auto",
slug,
},
});
expect(added.slug, "the dead endpoint registered anyway").toBe(slug);
const fetched = yield* client.mcp.getServer({ params: { slug } });
expect(fetched, "the stored server keeps the submitted config").toMatchObject({
slug,
config: {
transport: "remote",
endpoint: "http://127.0.0.1:1/mcp",
remoteTransport: "auto",
},
});
}),
);
scenario(
"Integrations · a connected MCP server's tool executes through the execution surface",
{},
Effect.scoped(
Effect.gen(function* () {
const target = yield* Target;
const apiSurface = yield* Api;
const server = yield* serveMcpServer(() =>
makeGreetingMcpServer({
name: "e2e-mcp",
toolDescription: "Echoes from the e2e MCP server",
text: "mcp-ok",
}),
);
const identity = yield* target.newIdentity();
const client = yield* apiSurface.client(api, identity);
const slug = newSlug("srcmcp");
yield* client.mcp.addServer({
payload: {
transport: "remote",
name: "E2E MCP",
endpoint: server.endpoint,
remoteTransport: "streamable-http",
slug,
},
});
yield* client.connections.create({
payload: {
owner: "org",
name: MAIN,
integration: slug,
template: NONE,
value: "unused",
},
});
const tools = yield* client.tools.list({ query: { integration: slug } });
const address = `tools.${slug}.org.main.simple_echo`;
expect(
tools.map((tool) => String(tool.address)),
"the discovered MCP tool is stamped on the connection",
).toContain(address);
const execution = completed(
yield* client.executions.execute({
payload: {
code: [`const result = await ${address}({});`, "return result;"].join("\n"),
},
}),
);
expect(execution.isError, "the execution succeeded").toBe(false);
expect(execution.structured, "the MCP tool's content came back").toMatchObject({
result: { ok: true, data: { content: [{ type: "text", text: "mcp-ok" }] } },
});
const requests = yield* server.requests;
expect(
requests.length,
"the live MCP server was dialed for discovery and again for the call",
).toBeGreaterThanOrEqual(2);
}),
),
);
scenario(
"Integrations · a connected GraphQL endpoint's query executes through the execution surface",
{},
Effect.scoped(
Effect.gen(function* () {
const target = yield* Target;
const apiSurface = yield* Api;
const server = yield* serveGraphqlTestServer({
schema: makeGreetingGraphqlSchema({ includeMutation: false }),
});
const identity = yield* target.newIdentity();
const client = yield* apiSurface.client(api, identity);
const slug = newSlug("srcgql");
const added = yield* client.graphql.addIntegration({
payload: { endpoint: server.endpoint, slug, name: "E2E GraphQL" },
});
expect(added.slug, "the integration keeps the requested slug").toBe(slug);
yield* client.connections.create({
payload: {
owner: "org",
name: MAIN,
integration: slug,
template: NONE,
value: "unused",
},
});
const tools = yield* client.tools.list({ query: { integration: slug } });
const address = `tools.${slug}.org.main.query.hello`;
expect(
tools.map((tool) => String(tool.address)),
"the introspected query is stamped as a tool",
).toContain(address);
const execution = completed(
yield* client.executions.execute({
payload: {
code: [`const result = await ${address}({ name: "Ada" });`, "return result;"].join(
"\n",
),
},
}),
);
expect(execution.isError, "the execution succeeded").toBe(false);
expect(execution.structured, "the resolver's greeting came back").toMatchObject({
result: { ok: true, data: { hello: "Hello Ada" } },
});
const requests = yield* server.requests;
expect(
requests.map((request) => request.payload.query ?? ""),
"the endpoint was introspected to build the tool catalog",
).toContainEqual(expect.stringContaining("__schema"));
expect(
requests.map((request) => request.payload.variables),
"the invocation's arguments reached the upstream resolver",
).toContainEqual({ name: "Ada" });
}),
),
);
scenario(
"Connections · org-shared and personal connections coexist with distinct tool addresses",
{},
Effect.gen(function* () {
const target = yield* Target;
const apiSurface = yield* Api;
const identity = yield* target.newIdentity();
const client = yield* apiSurface.client(api, identity);
const slug = newSlug("srcapi");
yield* client.openapi.addSpec({
payload: {
spec: { kind: "blob", value: pingSpec },
slug,
baseUrl: "http://127.0.0.1:59999",
},
});
yield* client.connections.create({
payload: {
owner: "org",
name: MAIN,
integration: slug,
template: API_KEY,
value: "org-secret",
},
});
yield* client.connections.create({
payload: {
owner: "user",
name: PERSONAL,
integration: slug,
template: API_KEY,
value: "personal-secret",
},
});
// Each connection stamps its own address-keyed copy of the tool.
const tools = yield* client.tools.list({ query: { integration: slug } });
const addresses = tools.map((tool) => String(tool.address));
expect(addresses, "the org connection has its own tool address").toContain(
`tools.${slug}.org.main.default.ping`,
);
expect(addresses, "the personal connection has its own tool address").toContain(
`tools.${slug}.user.personal.default.ping`,
);
// Owner filters separate the two credentials cleanly.
const userConnections = yield* client.connections.list({
query: { integration: slug, owner: "user" },
});
expect(
userConnections.map((c) => `${c.owner}/${String(c.name)}`),
"the user filter returns only the personal connection",
).toEqual(["user/personal"]);
const orgConnections = yield* client.connections.list({
query: { integration: slug, owner: "org" },
});
expect(
orgConnections.map((c) => `${c.owner}/${String(c.name)}`),
"the org filter returns only the shared connection",
).toEqual(["org/main"]);
}),
);
// The Cloudflare OpenAPI spec is the biggest real spec we care about: 16MB,
// 2700+ operations. Pushing it through the real HTTP + storage path is the
// load-bearing check that a storage regression (per-row writes, N+1 reads)
// shows up as a slow/failing scenario instead of a prod incident — and the
// symmetric remove must land cleanly too.
const CLOUDFLARE_SPEC_PATH = fileURLToPath(
new URL("../../packages/plugins/openapi/fixtures/cloudflare.json", import.meta.url),
);
scenario(
"Integrations · the full 16MB Cloudflare spec (2,700+ operations) registers and removes cleanly",
{ timeout: 180_000 },
Effect.gen(function* () {
const target = yield* Target;
const apiSurface = yield* Api;
const identity = yield* target.newIdentity();
const client = yield* apiSurface.client(api, identity);
const slug = newSlug("srccf");
const added = yield* client.openapi.addSpec({
payload: {
spec: { kind: "blob", value: readFileSync(CLOUDFLARE_SPEC_PATH, "utf-8") },
slug,
description: "Cloudflare API",
baseUrl: "https://api.cloudflare.com/client/v4",
},
});
expect(added.slug, "the giant spec registered").toBe(slug);
expect(added.toolCount, "thousands of operations were extracted").toBeGreaterThan(1000);
const listed = yield* client.integrations.list();
expect(
listed.map((i) => String(i.slug)),
"the integration is in the catalog",
).toContain(slug);
yield* client.integrations.remove({ params: { slug } });
const after = yield* client.integrations.list();
expect(
after.map((i) => String(i.slug)),
"the giant integration removes cleanly",
).not.toContain(slug);
}),
);