@desplega.ai/agent-swarm 1.129.0 → 1.131.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/README.md +2 -2
  2. package/dist/{actions-kfv2dawe.js → actions-w53mbns9.js} +11 -11
  3. package/dist/{anthropic-messages-3xgme8my.js → anthropic-messages-rjmd2e7n.js} +5 -5
  4. package/dist/{app-q8vjk6e8.js → app-m9gwqsqv.js} +8 -8
  5. package/dist/{artifact-hg4t1nx7.js → artifact-jysj3wrg.js} +2 -2
  6. package/dist/{assistant-g037r345.js → assistant-bp65m6f3.js} +13 -13
  7. package/dist/{azure-openai-responses-xa4sh9f6.js → azure-openai-responses-c0yjmbfd.js} +8 -5
  8. package/dist/{boot-reembed-18pzsrxa.js → boot-reembed-62p0at2k.js} +6 -6
  9. package/dist/{boot-reembed-wpks2cj8.js → boot-reembed-xmfp6wdh.js} +7 -7
  10. package/dist/{boot-scrub-logs-n7szd57r.js → boot-scrub-logs-rr8q2dms.js} +5 -5
  11. package/dist/{claude-adapter-qz4r0ajt.js → claude-adapter-2y47mrkd.js} +9 -9
  12. package/dist/{cli-mhjnbgb6.js → cli-0rcyq6d9.js} +450 -186
  13. package/dist/{cli-ttkmehy0.js → cli-2q72qz2s.js} +274 -25
  14. package/dist/{cli-gztgc3hz.js → cli-2wadx7p2.js} +2 -2
  15. package/dist/cli-3fj60etf.js +153 -0
  16. package/dist/{cli-7ecgm5v0.js → cli-3kf51j15.js} +1 -1
  17. package/dist/{cli-vgexpfsr.js → cli-57khth04.js} +6 -3
  18. package/dist/{cli-2mbe7vk0.js → cli-5dsbcjjw.js} +1 -1
  19. package/dist/{cli-etr62zy6.js → cli-5kx36evn.js} +2 -2
  20. package/dist/{cli-v2tr6amf.js → cli-5n6e5yfn.js} +30 -8
  21. package/dist/{cli-hx02s9zq.js → cli-5v4rw6yd.js} +2 -2
  22. package/dist/{cli-v37yr6mf.js → cli-5ze9rv97.js} +4 -4
  23. package/dist/{cli-ch7t5v7n.js → cli-6map995v.js} +9 -4
  24. package/dist/{cli-h0457a67.js → cli-70xqj0z3.js} +3 -3
  25. package/dist/{cli-kk4f9r17.js → cli-72q8m8gk.js} +8 -6
  26. package/dist/{cli-7padk69a.js → cli-78xwvkhj.js} +2 -2
  27. package/dist/{cli-dxtxacy7.js → cli-9dr5qzc0.js} +45 -8
  28. package/dist/{cli-17zxdgsq.js → cli-a40rnf71.js} +6 -6
  29. package/dist/{cli-t53vnnxz.js → cli-a4jzdpa3.js} +2514 -1055
  30. package/dist/{cli-w10fkrf1.js → cli-akdvwc9v.js} +354 -115
  31. package/dist/{cli-1qkk5er0.js → cli-bmze986d.js} +1 -1
  32. package/dist/{cli-ga12dc1d.js → cli-bqw0mt1n.js} +3 -3
  33. package/dist/{cli-0sf92efp.js → cli-cdeg08wx.js} +1 -1
  34. package/dist/{cli-a8ynhkyj.js → cli-cvgjwnh1.js} +17 -15
  35. package/dist/{cli-9fxg3v5m.js → cli-d2tfkcga.js} +4 -4
  36. package/dist/{cli-nhcd7x43.js → cli-d3x3x1c9.js} +2 -2
  37. package/dist/{cli-6nh2qxvh.js → cli-darcwax3.js} +1 -1
  38. package/dist/{cli-yjbgmysx.js → cli-e7ckcg4v.js} +12 -12
  39. package/dist/{cli-4n2gcjpd.js → cli-efxfnq6q.js} +4 -3
  40. package/dist/{cli-z9xqqhfk.js → cli-er3a4bb0.js} +1 -1
  41. package/dist/{cli-xg2eezyv.js → cli-f1am9szv.js} +1 -1
  42. package/dist/{cli-xy4cwsm9.js → cli-fywms69x.js} +1 -1
  43. package/dist/{cli-33jj76y8.js → cli-g6b8x1h8.js} +1 -1
  44. package/dist/{cli-epsvdckx.js → cli-gm9cbhbq.js} +20 -10
  45. package/dist/{cli-rkndnn90.js → cli-k9qkf1hw.js} +6 -4
  46. package/dist/{cli-zejvt395.js → cli-kh3ba2zf.js} +1 -1
  47. package/dist/{cli-gb25p1h2.js → cli-nm5gtp1x.js} +2 -2
  48. package/dist/{cli-akxnpx17.js → cli-pm6xbh84.js} +1829 -1629
  49. package/dist/{cli-2k0ztbfp.js → cli-psh3c4va.js} +1 -1
  50. package/dist/{cli-39vgrsep.js → cli-qv61hp37.js} +2 -2
  51. package/dist/{cli-hv2fndhm.js → cli-r6kqqbj0.js} +6 -4
  52. package/dist/{cli-1y1cm570.js → cli-rzbpmxdr.js} +1 -1
  53. package/dist/{cli-mmrk00vp.js → cli-t1xze5qh.js} +1 -1
  54. package/dist/{cli-g252a9ky.js → cli-t55yw3a1.js} +2 -2
  55. package/dist/{cli-7bz8dzqa.js → cli-t76vw5db.js} +1184 -1522
  56. package/dist/{cli-4n4mdv21.js → cli-xpxde7rm.js} +7 -3
  57. package/dist/{cli-fpaa5k2q.js → cli-yw8vghx2.js} +54 -18
  58. package/dist/cli-zsspvvm2.js +490 -0
  59. package/dist/cli.js +27 -25
  60. package/dist/{codex-adapter-7v6t7ff6.js → codex-adapter-d24q75wk.js} +7 -7
  61. package/dist/{codex-hook-amndawyb.js → codex-hook-hq54t9ft.js} +2 -2
  62. package/dist/{codex-session-runner-e7j4khe2.js → codex-session-runner-g50vcsex.js} +7 -7
  63. package/dist/{commands-ex0k5tbf.js → commands-c3nrc5hg.js} +5 -5
  64. package/dist/{db-df7jatfc.js → db-nt7fg3tw.js} +5 -5
  65. package/dist/{google-generative-ai-y42hnw9p.js → google-generative-ai-hysrd8qx.js} +7 -5
  66. package/dist/{google-vertex-4sg66gb6.js → google-vertex-p5arrga0.js} +7 -5
  67. package/dist/{handlers-1j2cfqt2.js → handlers-fkr6swat.js} +13 -13
  68. package/dist/{hook-nx9a0mj3.js → hook-77wpvnjc.js} +7 -7
  69. package/dist/{hook-w6yaf6sy.js → hook-g019yehy.js} +8 -8
  70. package/dist/{http-4tz5h8wg.js → http-jewj0syk.js} +2993 -716
  71. package/dist/{index-0bpkzb09.js → index-070v4eyb.js} +3 -3
  72. package/dist/{index-0s67qv7h.js → index-6gm5he8h.js} +11 -11
  73. package/dist/{index-35gtv6gj.js → index-7n2xpbd4.js} +310 -40
  74. package/dist/{index-ker3gccb.js → index-9znhar3x.js} +4 -4
  75. package/dist/{index-5n2c8yay.js → index-hase6zbe.js} +2 -2
  76. package/dist/{index-kcf3tm9h.js → index-hfvggd0z.js} +12 -12
  77. package/dist/{index-7c0jqna0.js → index-hp1kdbjj.js} +13 -13
  78. package/dist/{keepalive-3j4a9168.js → keepalive-j0fjvqfd.js} +7 -7
  79. package/dist/{lead-6kpevymb.js → lead-1n8x30xe.js} +33 -33
  80. package/dist/{maintenance-m1k82ean.js → maintenance-gvev11sa.js} +7 -7
  81. package/dist/{mistral-conversations-bjkdfb6z.js → mistral-conversations-81fwav0j.js} +6 -6
  82. package/dist/{oauth-refresh-sweep-881k8e4q.js → oauth-refresh-sweep-s9ecsvh0.js} +6 -6
  83. package/dist/{onboard-c0ykffjn.js → onboard-pvm5b38w.js} +2 -2
  84. package/dist/{openai-codex-responses-xetseqvt.js → openai-codex-responses-5g27pd6f.js} +43 -23
  85. package/dist/{openai-completions-5r2g5axa.js → openai-completions-3vkmfz2a.js} +55 -11
  86. package/dist/{openai-responses-ce67hd23.js → openai-responses-dg4t7j7a.js} +8 -5
  87. package/dist/{openrouter-images-pzfp22jb.js → openrouter-images-g3gm8931.js} +1 -1
  88. package/dist/{otel-impl-sqagjerv.js → otel-impl-p6jvgd9c.js} +6 -4
  89. package/dist/{otel-3mp81ppd.js → otel-nqa12wf3.js} +2 -2
  90. package/dist/{pi-mono-adapter-k584k16g.js → pi-mono-adapter-t091s27g.js} +17117 -7517
  91. package/dist/{pricing-refresh-y82whbf9.js → pricing-refresh-k49rcyed.js} +7 -7
  92. package/dist/{rbac-roles-nvkqmzyd.js → rbac-roles-30pspvy7.js} +7 -7
  93. package/dist/{rbac-roles-4ht8gegc.js → rbac-roles-cr80g96t.js} +6 -6
  94. package/dist/{render-v2-wvqdgvvp.js → render-v2-xm457ng1.js} +8 -8
  95. package/dist/{seed-pricing-fy3rxhde.js → seed-pricing-yhpv35fr.js} +6 -6
  96. package/dist/{setup-ak5cnc6f.js → setup-nytnmwwr.js} +2 -2
  97. package/dist/{worker-d8769q8a.js → worker-msytr2cw.js} +33 -33
  98. package/openapi.json +34039 -11036
  99. package/package.json +8 -6
  100. package/src/apps/definition.ts +368 -26
  101. package/src/apps/row-store.ts +66 -10
  102. package/src/apps/schema-migrate.ts +95 -1
  103. package/src/apps/store.ts +13 -4
  104. package/src/apps/sync-run-as.ts +18 -0
  105. package/src/apps/sync.ts +934 -0
  106. package/src/apps/version.ts +16 -2
  107. package/src/assets/key.ts +8 -1
  108. package/src/be/asset-key-audit.ts +3 -1
  109. package/src/be/db-queries/mcp-oauth.ts +297 -24
  110. package/src/be/db.ts +42 -1
  111. package/src/be/migrations/129_asset_keys_apps_scripts.sql +161 -0
  112. package/src/be/scripts/db.ts +5 -2
  113. package/src/be/scripts/typecheck.ts +1 -0
  114. package/src/be/seed-scripts/catalog/app-sync-run.ts +32 -0
  115. package/src/be/seed-scripts/catalog/github-issues-pull.ts +102 -0
  116. package/src/be/seed-scripts/index.ts +18 -0
  117. package/src/be/seed-skills/index.ts +7 -0
  118. package/src/http/active-sessions.ts +26 -18
  119. package/src/http/agents.ts +94 -27
  120. package/src/http/api-keys.ts +91 -17
  121. package/src/http/approval-requests.ts +87 -10
  122. package/src/http/apps.ts +361 -53
  123. package/src/http/assets.ts +165 -31
  124. package/src/http/budgets.ts +7 -5
  125. package/src/http/codex-oauth-keep-warm.ts +21 -3
  126. package/src/http/config.ts +46 -16
  127. package/src/http/context.ts +33 -6
  128. package/src/http/ecosystem.ts +20 -6
  129. package/src/http/events.ts +24 -9
  130. package/src/http/favorites.ts +20 -6
  131. package/src/http/fs.ts +60 -17
  132. package/src/http/heartbeat.ts +18 -4
  133. package/src/http/inbox-state.ts +12 -6
  134. package/src/http/integrations.ts +25 -5
  135. package/src/http/kv.ts +36 -15
  136. package/src/http/mcp-bridge.ts +5 -1
  137. package/src/http/mcp-oauth.ts +332 -17
  138. package/src/http/mcp-servers.ts +56 -18
  139. package/src/http/memory.ts +282 -29
  140. package/src/http/metrics.ts +80 -17
  141. package/src/http/oauth-callback.ts +10 -4
  142. package/src/http/oauth-generic.ts +5 -1
  143. package/src/http/oauth-locks.ts +6 -3
  144. package/src/http/openapi.ts +57 -9
  145. package/src/http/page-proxy.ts +25 -5
  146. package/src/http/pages-public.ts +37 -20
  147. package/src/http/pages.ts +93 -28
  148. package/src/http/poll.ts +89 -5
  149. package/src/http/pricing.ts +9 -6
  150. package/src/http/prompt-templates.ts +85 -21
  151. package/src/http/route-def.ts +67 -4
  152. package/src/http/schedules.ts +63 -14
  153. package/src/http/script-connection-proxy.ts +30 -4
  154. package/src/http/script-connections.ts +393 -43
  155. package/src/http/script-runs.ts +73 -19
  156. package/src/http/scripts.ts +257 -39
  157. package/src/http/session-data.ts +87 -14
  158. package/src/http/sessions.ts +80 -5
  159. package/src/http/skills.ts +115 -35
  160. package/src/http/stats.ts +94 -13
  161. package/src/http/task-templates.ts +6 -4
  162. package/src/http/tasks.ts +230 -61
  163. package/src/http/trackers/jira.ts +90 -30
  164. package/src/http/trackers/linear.ts +46 -12
  165. package/src/http/users.ts +162 -25
  166. package/src/http/utils.ts +12 -2
  167. package/src/http/webhooks.ts +30 -16
  168. package/src/http/workflow-events.ts +18 -5
  169. package/src/http/workflows.ts +128 -39
  170. package/src/http/x.ts +37 -6
  171. package/src/oauth/ensure-mcp-token.ts +16 -1
  172. package/src/oauth/mcp-wrapper.ts +281 -26
  173. package/src/providers/pi-mono-adapter.ts +1 -1
  174. package/src/scripts-runtime/credential-broker/README.md +1 -1
  175. package/src/scripts-runtime/credential-broker/fetch-patch.ts +12 -2
  176. package/src/scripts-runtime/sdk-allowlist.ts +1 -0
  177. package/src/scripts-runtime/stdlib/fetch.ts +6 -0
  178. package/src/scripts-runtime/types/stdlib.d.ts +1 -0
  179. package/src/scripts-runtime/types/swarm-sdk.d.ts +1 -0
  180. package/src/server.ts +2 -0
  181. package/src/tests/apps-rbac.test.ts +110 -0
  182. package/src/tests/apps-spike2.test.ts +4 -1
  183. package/src/tests/apps-sync-engine.test.ts +2540 -0
  184. package/src/tests/apps-sync.test.ts +1627 -0
  185. package/src/tests/asset-key-api.test.ts +48 -2
  186. package/src/tests/asset-key-invariants.test.ts +92 -0
  187. package/src/tests/asset-key-migration.test.ts +174 -8
  188. package/src/tests/asset-key-normalization.test.ts +2 -0
  189. package/src/tests/credential-broker.test.ts +27 -2
  190. package/src/tests/mcp-oauth-dcr-reuse.test.ts +743 -0
  191. package/src/tests/mcp-oauth-ensure-token.test.ts +45 -0
  192. package/src/tests/mcp-oauth-manual-client.test.ts +135 -2
  193. package/src/tests/mcp-oauth-queries.test.ts +153 -0
  194. package/src/tests/mcp-oauth-wrapper.test.ts +432 -0
  195. package/src/tests/memory-http-recall-gating.test.ts +2 -0
  196. package/src/tests/openapi-response-contract.test.ts +138 -0
  197. package/src/tests/rbac-admission-e2e.test.ts +68 -0
  198. package/src/tests/script-connections.test.ts +3 -0
  199. package/src/tests/scripts-runtime-fetch.test.ts +121 -0
  200. package/src/tests/scripts-runtime-secret-egress.test.ts +4 -2
  201. package/src/tests/seed-scripts.test.ts +2 -2
  202. package/src/tests/swarm-tool-result-gate.test.ts +32 -0
  203. package/src/tests/task-working-dir.test.ts +8 -4
  204. package/src/tests/whoami-route.test.ts +127 -0
  205. package/src/tests/workflow-engine-v2.test.ts +80 -7
  206. package/src/tests/workflow-swarm-script.test.ts +104 -0
  207. package/src/tools/app-get.ts +10 -2
  208. package/src/tools/app-rollback.ts +1 -0
  209. package/src/tools/app-sync.ts +112 -0
  210. package/src/tools/script-common.ts +20 -0
  211. package/src/tools/tool-config.ts +2 -1
  212. package/src/tools/utils.ts +11 -0
  213. package/src/tools/workflows/create-workflow.ts +4 -1
  214. package/src/types.ts +1394 -1206
  215. package/src/utils/template.ts +8 -1
  216. package/src/utils/zod-openapi.ts +11 -0
  217. package/src/workflows/engine.ts +27 -4
  218. package/src/workflows/executors/swarm-script.ts +28 -0
  219. package/src/workflows/retry-poller.ts +19 -2
  220. package/templates/skills/apps/content.md +94 -5
  221. package/templates/skills/asset-namespaces/content.md +2 -2
  222. package/templates/skills/scheduled-task-resilience/SKILL.md +102 -0
  223. package/templates/skills/scheduled-task-resilience/config.json +14 -0
  224. package/templates/skills/scheduled-task-resilience/content.md +97 -0
  225. package/dist/cli-7wmybrt5.js +0 -115
  226. package/dist/cli-d91pvmq1.js +0 -14
@@ -2,6 +2,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test
2
2
  import { unlink } from "node:fs/promises";
3
3
  import { closeDb, createMcpServer, initDb } from "../be/db";
4
4
  import {
5
+ findReusableMcpOAuthClient,
5
6
  getMcpOAuthToken,
6
7
  type UpsertMcpOAuthTokenInput,
7
8
  upsertMcpOAuthToken,
@@ -144,6 +145,29 @@ describe("ensureMcpToken", () => {
144
145
  expect(calls).toBe(1);
145
146
  });
146
147
 
148
+ test("uses body-post authentication for a legacy row with no recorded method", async () => {
149
+ const input = makeToken({
150
+ expiresAt: new Date(Date.now() + 30_000).toISOString(),
151
+ tokenEndpointAuthMethod: null,
152
+ });
153
+ upsertMcpOAuthToken(input);
154
+
155
+ globalThis.fetch = async (_url: string | URL | Request, init?: RequestInit) => {
156
+ const headers = init?.headers as Record<string, string>;
157
+ const params = new URLSearchParams((init?.body as string) ?? "");
158
+ expect(headers.Authorization).toBeUndefined();
159
+ expect(params.get("client_id")).toBe("client-abc");
160
+ expect(params.get("client_secret")).toBe("secret-xyz");
161
+ return new Response(JSON.stringify({ access_token: "refreshed-access", expires_in: 3600 }), {
162
+ status: 200,
163
+ headers: { "Content-Type": "application/json" },
164
+ });
165
+ };
166
+
167
+ const token = await ensureMcpToken(input.mcpServerId);
168
+ expect(token!.accessToken).toBe("refreshed-access");
169
+ });
170
+
147
171
  test("flips status to 'error' on refresh failure", async () => {
148
172
  const input = makeToken({
149
173
  expiresAt: new Date(Date.now() + 30_000).toISOString(),
@@ -160,6 +184,27 @@ describe("ensureMcpToken", () => {
160
184
  expect(reread!.status).toBe("error");
161
185
  });
162
186
 
187
+ test("invalidates the stored DCR client on an invalid_client refresh failure (automatic path)", async () => {
188
+ const input = makeToken({
189
+ expiresAt: new Date(Date.now() + 30_000).toISOString(), // within 5-min buffer
190
+ });
191
+ upsertMcpOAuthToken(input);
192
+
193
+ // The automatic refresh path (ensureMcpToken, used by the proxy/server
194
+ // resolution) must invalidate the stored client on invalid_client just
195
+ // like the explicit POST /refresh route does — otherwise a client the
196
+ // provider has disowned stays "reusable" forever.
197
+ expect(findReusableMcpOAuthClient(input.mcpServerId)).not.toBeNull();
198
+
199
+ globalThis.fetch = async () =>
200
+ new Response(JSON.stringify({ error: "invalid_client" }), { status: 401 });
201
+
202
+ const token = await ensureMcpToken(input.mcpServerId);
203
+ expect(token!.status).toBe("error");
204
+
205
+ expect(findReusableMcpOAuthClient(input.mcpServerId)).toBeNull();
206
+ });
207
+
163
208
  test("concurrent calls dedupe via per-key inflight mutex", async () => {
164
209
  const input = makeToken({
165
210
  expiresAt: new Date(Date.now() + 30_000).toISOString(),
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
2
  import { unlink } from "node:fs/promises";
3
3
  import type { IncomingMessage, ServerResponse } from "node:http";
4
4
  import { Readable } from "node:stream";
5
- import { closeDb, createMcpServer, initDb } from "../be/db";
5
+ import { closeDb, createMcpServer, getDb, initDb } from "../be/db";
6
6
  import { getMcpOAuthToken } from "../be/db-queries/mcp-oauth";
7
7
  import { handleCore } from "../http/core";
8
8
  import { handleMcpOAuth } from "../http/mcp-oauth";
@@ -89,14 +89,17 @@ async function dispatch(path: string, init: RequestInit = {}): Promise<TestRespo
89
89
  describe("MCP OAuth manual client flow", () => {
90
90
  let originalFetch: typeof fetch;
91
91
  let capturedTokenBody: string | null;
92
+ let capturedTokenHeaders: Record<string, string> | null;
92
93
  let originalPublicMcpBaseUrl: string | undefined;
93
94
  let originalAppUrl: string | undefined;
94
95
  let originalDashboardUrl: string | undefined;
95
96
  let includeRefreshToken: boolean;
97
+ let asAuthMethodsSupported: string[] | null = null;
96
98
 
97
99
  beforeEach(async () => {
98
100
  originalFetch = globalThis.fetch;
99
101
  capturedTokenBody = null;
102
+ capturedTokenHeaders = null;
100
103
  originalPublicMcpBaseUrl = process.env.PUBLIC_MCP_BASE_URL;
101
104
  originalAppUrl = process.env.APP_URL;
102
105
  originalDashboardUrl = process.env.DASHBOARD_URL;
@@ -111,8 +114,27 @@ describe("MCP OAuth manual client flow", () => {
111
114
 
112
115
  globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
113
116
  const href = input.toString();
117
+ // Discovery fixture for manual clients that omit an endpoint, so the
118
+ // route falls through to discoverForMcp.
119
+ if (href === "https://disc.example.test/.well-known/oauth-protected-resource") {
120
+ return Response.json({
121
+ resource: "https://disc.example.test/mcp",
122
+ authorization_servers: ["https://as-disc.example.test"],
123
+ });
124
+ }
125
+ if (href === "https://as-disc.example.test/.well-known/oauth-authorization-server") {
126
+ return Response.json({
127
+ issuer: "https://as-disc.example.test",
128
+ authorization_endpoint: "https://as-disc.example.test/authorize",
129
+ token_endpoint: "https://as-disc.example.test/token",
130
+ ...(asAuthMethodsSupported === null
131
+ ? {}
132
+ : { token_endpoint_auth_methods_supported: asAuthMethodsSupported }),
133
+ });
134
+ }
114
135
  if (href === "https://login.salesforce.com/services/oauth2/token") {
115
136
  capturedTokenBody = init?.body?.toString() ?? null;
137
+ capturedTokenHeaders = (init?.headers as Record<string, string> | undefined) ?? null;
116
138
  return new Response(
117
139
  JSON.stringify({
118
140
  access_token: "sf-access-token",
@@ -140,7 +162,107 @@ describe("MCP OAuth manual client flow", () => {
140
162
  else process.env.DASHBOARD_URL = originalDashboardUrl;
141
163
  });
142
164
 
143
- test("authorize-url uses a stored manual client when DCR is not available", async () => {
165
+ async function registerDiscoveredManualClient(name: string, body: Record<string, unknown> = {}) {
166
+ const mcpServer = createMcpServer({
167
+ name,
168
+ transport: "http",
169
+ url: "https://disc.example.test/mcp",
170
+ scope: "swarm",
171
+ });
172
+ // No authorizeUrl/tokenUrl, so the route runs discovery.
173
+ const res = await dispatch(`/api/mcp-oauth/${mcpServer.id}/manual-client`, {
174
+ method: "POST",
175
+ headers: { Authorization: `Bearer ${API_KEY}` },
176
+ body: JSON.stringify({ clientId: "disc-client", clientSecret: "disc-secret", ...body }),
177
+ });
178
+ expect(res.status).toBe(200);
179
+ return mcpServer;
180
+ }
181
+
182
+ test("discovery does not switch an omitted manual method to Basic", async () => {
183
+ // AS metadata describes what the SERVER accepts, not the method assigned
184
+ // to this out-of-band client. A pre-registered client working on body-post
185
+ // must not be flipped just because the AS also supports Basic.
186
+ asAuthMethodsSupported = ["client_secret_basic", "client_secret_post"];
187
+ const mcpServer = await registerDiscoveredManualClient("manual-disc-both");
188
+ expect(getMcpOAuthToken(mcpServer.id)?.tokenEndpointAuthMethod).toBe("client_secret_post");
189
+ });
190
+
191
+ test("an AS advertising no methods still leaves an omitted manual method on body-post", async () => {
192
+ asAuthMethodsSupported = null;
193
+ const mcpServer = await registerDiscoveredManualClient("manual-disc-absent");
194
+ expect(getMcpOAuthToken(mcpServer.id)?.tokenEndpointAuthMethod).toBe("client_secret_post");
195
+ });
196
+
197
+ test("an AS that excludes body-post does switch the omitted manual method", async () => {
198
+ // Here the legacy default is knowably broken, so defer to the server.
199
+ asAuthMethodsSupported = ["client_secret_basic"];
200
+ const mcpServer = await registerDiscoveredManualClient("manual-disc-basic-only");
201
+ expect(getMcpOAuthToken(mcpServer.id)?.tokenEndpointAuthMethod).toBe("client_secret_basic");
202
+ });
203
+
204
+ test("an explicit method still wins over discovery", async () => {
205
+ asAuthMethodsSupported = ["client_secret_basic"];
206
+ const mcpServer = await registerDiscoveredManualClient("manual-disc-explicit", {
207
+ tokenEndpointAuthMethod: "client_secret_post",
208
+ });
209
+ expect(getMcpOAuthToken(mcpServer.id)?.tokenEndpointAuthMethod).toBe("client_secret_post");
210
+ });
211
+
212
+ test("a manual client created without an explicit method records body-post, not Basic", async () => {
213
+ // Both endpoints are supplied, so discovery never runs and never selects a
214
+ // method. The dashboard posts no tokenEndpointAuthMethod either, so
215
+ // defaulting to Basic here would break every UI-created manual client that
216
+ // works today on body-post.
217
+ const mcpServer = createMcpServer({
218
+ name: "manual-no-method",
219
+ transport: "http",
220
+ url: "https://api.example.com/mcp",
221
+ scope: "swarm",
222
+ });
223
+
224
+ const res = await dispatch(`/api/mcp-oauth/${mcpServer.id}/manual-client`, {
225
+ method: "POST",
226
+ headers: { Authorization: `Bearer ${API_KEY}` },
227
+ body: JSON.stringify({
228
+ clientId: "manual-client-id",
229
+ clientSecret: "manual-client-secret",
230
+ authorizationServerIssuer: "https://as.example.com",
231
+ authorizeUrl: "https://as.example.com/authorize",
232
+ tokenUrl: "https://as.example.com/token",
233
+ }),
234
+ });
235
+ expect(res.status).toBe(200);
236
+
237
+ expect(getMcpOAuthToken(mcpServer.id)?.tokenEndpointAuthMethod).toBe("client_secret_post");
238
+ });
239
+
240
+ test("an explicit method on the manual-client route still wins", async () => {
241
+ const mcpServer = createMcpServer({
242
+ name: "manual-explicit-method",
243
+ transport: "http",
244
+ url: "https://api.example.com/mcp2",
245
+ scope: "swarm",
246
+ });
247
+
248
+ const res = await dispatch(`/api/mcp-oauth/${mcpServer.id}/manual-client`, {
249
+ method: "POST",
250
+ headers: { Authorization: `Bearer ${API_KEY}` },
251
+ body: JSON.stringify({
252
+ clientId: "manual-client-id",
253
+ clientSecret: "manual-client-secret",
254
+ authorizationServerIssuer: "https://as.example.com",
255
+ authorizeUrl: "https://as.example.com/authorize",
256
+ tokenUrl: "https://as.example.com/token",
257
+ tokenEndpointAuthMethod: "client_secret_basic",
258
+ }),
259
+ });
260
+ expect(res.status).toBe(200);
261
+
262
+ expect(getMcpOAuthToken(mcpServer.id)?.tokenEndpointAuthMethod).toBe("client_secret_basic");
263
+ });
264
+
265
+ test("a legacy manual client re-authorizes with body-post authentication", async () => {
144
266
  const mcpServer = createMcpServer({
145
267
  name: "salesforce-sobjects",
146
268
  transport: "http",
@@ -168,6 +290,14 @@ describe("MCP OAuth manual client flow", () => {
168
290
  expect(provisionalToken?.clientSource).toBe("manual");
169
291
  expect(provisionalToken?.status).toBe("error");
170
292
 
293
+ // Simulate a manual client that was stored before tokenEndpointAuthMethod
294
+ // existed. Reauthorization must preserve its historical body-post method.
295
+ getDb()
296
+ .query(
297
+ "UPDATE oauth_apps SET metadata = json_remove(metadata, '$.tokenEndpointAuthMethod') WHERE provider = ?",
298
+ )
299
+ .run(`mcp-${mcpServer.id}`);
300
+
171
301
  const authorizeRes = await dispatch(`/api/mcp-oauth/${mcpServer.id}/authorize-url`, {
172
302
  headers: { Authorization: `Bearer ${API_KEY}` },
173
303
  });
@@ -196,6 +326,8 @@ describe("MCP OAuth manual client flow", () => {
196
326
  `${process.env.APP_URL}/mcp-servers/${mcpServer.id}?oauth=success`,
197
327
  );
198
328
 
329
+ // The stored method is absent, so this legacy manual client must retain
330
+ // the body-post behavior that worked before the auth-method field existed.
199
331
  const tokenRequest = new URLSearchParams(capturedTokenBody ?? "");
200
332
  expect(tokenRequest.get("client_id")).toBe("sf-client-id");
201
333
  expect(tokenRequest.get("client_secret")).toBe("sf-client-secret");
@@ -203,6 +335,7 @@ describe("MCP OAuth manual client flow", () => {
203
335
  expect(tokenRequest.get("redirect_uri")).toBe(
204
336
  "https://swarm.example.test/api/mcp-oauth/callback",
205
337
  );
338
+ expect(capturedTokenHeaders?.Authorization).toBeUndefined();
206
339
 
207
340
  const connectedToken = getMcpOAuthToken(mcpServer.id);
208
341
  expect(connectedToken?.clientSource).toBe("manual");
@@ -13,10 +13,12 @@ import {
13
13
  applyMcpOAuthRefresh,
14
14
  consumeMcpOAuthPending,
15
15
  deleteMcpOAuthToken,
16
+ findReusableMcpOAuthClient,
16
17
  gcMcpOAuthPending,
17
18
  getMcpOAuthToken,
18
19
  getMcpServerAuthMethod,
19
20
  insertMcpOAuthPending,
21
+ invalidateMcpOAuthClient,
20
22
  isMcpTokenExpiringSoon,
21
23
  listMcpOAuthTokensForMcp,
22
24
  markMcpOAuthTokenStatus,
@@ -374,6 +376,157 @@ describe("mcp_oauth_pending (state PK)", () => {
374
376
  });
375
377
  });
376
378
 
379
+ describe("findReusableMcpOAuthClient / invalidateMcpOAuthClient", () => {
380
+ test("returns null when nothing has ever been registered", () => {
381
+ const server = makeServer("mcp-reuse-none");
382
+ expect(findReusableMcpOAuthClient(server.id)).toBeNull();
383
+ });
384
+
385
+ test("reuses a connected token's DCR client (re-authorize case)", () => {
386
+ const server = makeServer("mcp-reuse-connected");
387
+ upsertMcpOAuthToken({
388
+ ...base(server.id),
389
+ authorizationServerIssuer: "https://issuer.example.com",
390
+ registrationEndpoint: "https://issuer.example.com/register",
391
+ });
392
+
393
+ const reusable = findReusableMcpOAuthClient(server.id);
394
+ expect(reusable).toMatchObject({
395
+ clientId: "client-abc",
396
+ clientSecret: "dcr-secret-xyz",
397
+ authorizationServerIssuer: "https://issuer.example.com",
398
+ registrationEndpoint: "https://issuer.example.com/register",
399
+ clientSource: "dcr",
400
+ });
401
+ });
402
+
403
+ test("upsertMcpOAuthToken persists redirectUri onto the app row (first-connect reuse case)", () => {
404
+ const server = makeServer("mcp-reuse-connected-redirect-uri");
405
+ // Before this fix, upsertMcpOAuthToken never passed redirectUri through
406
+ // to upsertMcpApp, so the FIRST successful connect (which always creates
407
+ // a brand new oauth_apps row here, since the pending row's app was
408
+ // already deleted as an orphan by consumeMcpOAuthPending) left
409
+ // redirectUri as "" — silently failing every subsequent
410
+ // `reusable.redirectUri === callbackRedirectUri()` reuse check and
411
+ // forcing a fresh DCR registration on every re-authorize.
412
+ upsertMcpOAuthToken({
413
+ ...base(server.id),
414
+ redirectUri: "https://swarm.example.com/api/mcp-oauth/callback",
415
+ });
416
+
417
+ const reusable = findReusableMcpOAuthClient(server.id);
418
+ expect(reusable?.redirectUri).toBe("https://swarm.example.com/api/mcp-oauth/callback");
419
+ });
420
+
421
+ test("reuses a still-live pending's client when no token exists yet", () => {
422
+ const server = makeServer("mcp-reuse-pending");
423
+ insertMcpOAuthPending({
424
+ state: "reuse-pending-state",
425
+ mcpServerId: server.id,
426
+ codeVerifier: "verifier",
427
+ resourceUrl: "https://mcp.example.com/",
428
+ authorizationServerIssuer: "https://issuer.example.com",
429
+ registrationEndpoint: "https://issuer.example.com/register",
430
+ authorizeUrl: "https://issuer.example.com/authorize",
431
+ tokenUrl: "https://issuer.example.com/token",
432
+ dcrClientId: "pending-client",
433
+ dcrClientSecret: "pending-secret",
434
+ redirectUri: "https://swarm.example.com/cb",
435
+ });
436
+
437
+ // The pending row itself is still live (not consumed/GC'd) — a second
438
+ // authorize attempt before completion must see the same client.
439
+ const reusable = findReusableMcpOAuthClient(server.id);
440
+ expect(reusable).toMatchObject({
441
+ clientId: "pending-client",
442
+ clientSecret: "pending-secret",
443
+ authorizationServerIssuer: "https://issuer.example.com",
444
+ registrationEndpoint: "https://issuer.example.com/register",
445
+ });
446
+
447
+ // A second pending attempt for the same connector+user reuses the same
448
+ // underlying app row instead of creating a new one (row-churn guard).
449
+ const before = getDb()
450
+ .query<{ count: number }, [string]>(
451
+ "SELECT count(*) AS count FROM oauth_apps WHERE mcpServerId = ?",
452
+ )
453
+ .get(server.id)?.count;
454
+ insertMcpOAuthPending({
455
+ state: "reuse-pending-state-2",
456
+ mcpServerId: server.id,
457
+ codeVerifier: "verifier-2",
458
+ resourceUrl: "https://mcp.example.com/",
459
+ authorizationServerIssuer: "https://issuer.example.com",
460
+ registrationEndpoint: "https://issuer.example.com/register",
461
+ authorizeUrl: "https://issuer.example.com/authorize",
462
+ tokenUrl: "https://issuer.example.com/token",
463
+ dcrClientId: "pending-client",
464
+ dcrClientSecret: "pending-secret",
465
+ redirectUri: "https://swarm.example.com/cb",
466
+ });
467
+ const after = getDb()
468
+ .query<{ count: number }, [string]>(
469
+ "SELECT count(*) AS count FROM oauth_apps WHERE mcpServerId = ?",
470
+ )
471
+ .get(server.id)?.count;
472
+ expect(after).toBe(before);
473
+ });
474
+
475
+ test("manual clientSource is never surfaced through the reuse path", () => {
476
+ const server = makeServer("mcp-reuse-manual");
477
+ upsertMcpOAuthToken({ ...base(server.id), clientSource: "manual" });
478
+ expect(findReusableMcpOAuthClient(server.id)).toBeNull();
479
+ });
480
+
481
+ test("invalidate flips the flag; a subsequent lookup misses until the next legitimate write", () => {
482
+ const server = makeServer("mcp-reuse-invalidate");
483
+ upsertMcpOAuthToken(base(server.id));
484
+ expect(findReusableMcpOAuthClient(server.id)).not.toBeNull();
485
+
486
+ invalidateMcpOAuthClient(server.id);
487
+ expect(findReusableMcpOAuthClient(server.id)).toBeNull();
488
+
489
+ // A fresh legitimate write (e.g. re-registering after invalidation)
490
+ // clears the flag again.
491
+ upsertMcpOAuthToken({ ...base(server.id), accessToken: "fresh-access" });
492
+ expect(findReusableMcpOAuthClient(server.id)).not.toBeNull();
493
+ });
494
+
495
+ test("invalidate on an unknown connector is a no-op", () => {
496
+ expect(() => invalidateMcpOAuthClient("00000000-0000-0000-0000-000000000000")).not.toThrow();
497
+ });
498
+
499
+ test("invalidate is idempotent for an already-invalidated client", () => {
500
+ const server = makeServer("mcp-reuse-invalidate-idempotent");
501
+ upsertMcpOAuthToken(base(server.id));
502
+
503
+ invalidateMcpOAuthClient(server.id);
504
+ expect(findReusableMcpOAuthClient(server.id)).toBeNull();
505
+
506
+ // A second invalidate call against the SAME still-invalidated client
507
+ // must not throw and must not disturb the invalidated state (this is
508
+ // what "cap invalidation to once per client_id" means in practice — the
509
+ // other call sites can all observe the same failure and each call this,
510
+ // but only the first one actually does anything).
511
+ expect(() => invalidateMcpOAuthClient(server.id)).not.toThrow();
512
+ expect(findReusableMcpOAuthClient(server.id)).toBeNull();
513
+ });
514
+
515
+ test("disconnect clears the stored DCR client so Reconnect forces a fresh registration", () => {
516
+ const server = makeServer("mcp-disconnect-clears-client");
517
+ upsertMcpOAuthToken(base(server.id));
518
+ expect(findReusableMcpOAuthClient(server.id)).not.toBeNull();
519
+
520
+ expect(deleteMcpOAuthToken(server.id)).toBe(true);
521
+
522
+ // Disconnect is the canonical user recovery gesture — before this fix,
523
+ // deleteMcpOAuthToken only soft-revoked oauth_authorizations and left
524
+ // oauth_apps untouched, so a Reconnect silently got the same client_id
525
+ // back (rawMcpToken has no status filter).
526
+ expect(findReusableMcpOAuthClient(server.id)).toBeNull();
527
+ });
528
+ });
529
+
377
530
  describe("mcp_servers.extraAuthorizeParams round-trip", () => {
378
531
  test("createMcpServer persists extraAuthorizeParams", () => {
379
532
  const server = createMcpServer({