@devries-cameron20 / composio-1 / commits / adb255305
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

docs(examples): add session approvals with CI coverage (#4935)

This PR: - adds runnable TypeScript and Python Session approval examples for approve, deny, decline, cancel, and Always approve, using read-only Hacker News calls without model keys or connected accounts - demonstrates `COMPOSIO_MULTI_EXECUTE_TOOL` continuation with all input-request IDs and the opaque request state preserved, plus an MCP client with form elicitation and an explicit deny fallback - runs deterministic example tests in the existing TypeScript and Python PR workflows and registers three unattended entries in the nightly/manual staging manifest sweep - links the runnable examples and local commands from the approvals guide and Python examples index - regenerates the workspace lockfile with pinned pnpm for the new private examples package; this also applies existing overrides to stale MCP transitive resolutions - passes 17 TypeScript tests (`pnpm --filter approvals-example test`) and 11 Python tests (`uv run --project python pytest python/tests/test_approval_examples.py -q`) - passes focused TypeScript/Python type checks and lint, example validation, documentation link checks, agent-guidance validators, and actionlint for the changed workflows - leaves live backend validation explicit: it was not run locally because `COMPOSIO_API_KEY` was unavailable; live staging checks run nightly or on demand, separately from deterministic PR checks

Alberto Schiabel committed Oct 16, 2026 at 19:17 UTC adb255305dec82d5605e6c23a4109f35ccdfee85
22 files changed +1238 -101
.github/workflows/py.test.yml
+2
@@ -242,12 +242,14 @@ jobs:
242 cd python/
243 source .venv/bin/activate
244 ruff check --config config/ruff.toml composio/ tests/
245 + ruff check --config config/ruff.toml examples/approvals.py examples/verify_approvals.py
246
247 - name: Run Ruff Formatter Check
248 run: |
249 cd python/
250 source .venv/bin/activate
251 ruff format --check --config config/ruff.toml composio/ tests/
252 + ruff format --check --config config/ruff.toml examples/approvals.py examples/verify_approvals.py
253
254 integration-tests:
255 name: Integration Tests
.github/workflows/ts.examples.yml
+3
@@ -68,6 +68,9 @@ jobs:
68 - name: Lint examples
69 run: pnpm run lint:examples
70
71 + - name: Test approval examples and MCP elicitation
72 + run: pnpm --filter approvals-example test
73 +
74 # Prove the Cloudflare Workers entry bundles without secrets or deploying.
75 - name: Cloudflare Workers dry-run build
76 run: pnpm exec turbo cf:dry-run --filter='./ts/examples/*'
docs/content/docs/approvals.mdx
+4
@@ -445,6 +445,10 @@ terminal.close();
445 </Tab>
446 </Tabs>
447
448 +## Runnable examples
449 +
450 +Try the [TypeScript and Python approval examples](https://github.com/ComposioHQ/composio/tree/next/ts/examples/approvals) for a minimal tool call, a multi-tool batch, and an MCP client with elicitation. They use read-only Hacker News calls, so you don't need a connected account or model API key. The examples include tests for CI and unattended staging checks for approve, deny, decline, cancel, and **Always approve**.
451 +
452 ## Next
453
454 <Card
examples-manifest.json
+64
@@ -1291,6 +1291,70 @@
1291 "./python/providers/openai_agents",
1292 "./python"
1293 ]
1294 + },
1295 + {
1296 + "id": "ts/approvals/verify",
1297 + "lang": "ts",
1298 + "file": "ts/examples/approvals/src/verify.ts",
1299 + "tier": "1",
1300 + "env": [
1301 + "COMPOSIO_API_KEY"
1302 + ],
1303 + "toolkits": [
1304 + "hackernews"
1305 + ],
1306 + "timeoutSec": 180,
1307 + "pkg": "approvals-example"
1308 + },
1309 + {
1310 + "id": "ts/approvals/verify-mcp",
1311 + "lang": "ts",
1312 + "file": "ts/examples/approvals/src/verify-mcp.ts",
1313 + "tier": "1",
1314 + "env": [
1315 + "COMPOSIO_API_KEY"
1316 + ],
1317 + "toolkits": [
1318 + "hackernews"
1319 + ],
1320 + "timeoutSec": 180,
1321 + "pkg": "approvals-example"
1322 + },
1323 + {
1324 + "id": "py/approvals/verify",
1325 + "lang": "py",
1326 + "file": "python/examples/verify_approvals.py",
1327 + "tier": "1",
1328 + "env": [
1329 + "COMPOSIO_API_KEY"
1330 + ],
1331 + "toolkits": [
1332 + "hackernews"
1333 + ],
1334 + "timeoutSec": 180
1335 + },
1336 + {
1337 + "id": "ts/approvals/terminal",
1338 + "lang": "ts",
1339 + "file": "ts/examples/approvals/src/index.ts",
1340 + "tier": "X",
1341 + "reason": "stdin-repl; unattended verification has dedicated tier-1 entries",
1342 + "pkg": "approvals-example"
1343 + },
1344 + {
1345 + "id": "ts/approvals/mcp",
1346 + "lang": "ts",
1347 + "file": "ts/examples/approvals/src/mcp.ts",
1348 + "tier": "X",
1349 + "reason": "stdin-repl; unattended verification has dedicated tier-1 entries",
1350 + "pkg": "approvals-example"
1351 + },
1352 + {
1353 + "id": "py/approvals/terminal",
1354 + "lang": "py",
1355 + "file": "python/examples/approvals.py",
1356 + "tier": "X",
1357 + "reason": "stdin-repl; unattended verification has dedicated tier-1 entries"
1358 }
1359 ]
1360 }
pnpm-lock.yaml
+39 -101
@@ -478,10 +478,10 @@ importers:
478 version: link:../../../../packages/providers/mastra
479 '@mastra/core':
480 specifier: 'catalog:'
481 - version: 1.53.0(@cfworker/json-schema@4.1.1)(ai@6.0.303(zod@3.25.76))(express@5.3.0)(supports-color@10.2.2)(zod@3.25.76)
481 + version: 1.53.0(@cfworker/json-schema@4.1.1)(ai@6.0.303(zod@3.25.76))(express@5.3.0)(zod@3.25.76)
482 '@mastra/mcp':
483 specifier: 1.17.2
484 - version: 1.17.2(@cfworker/json-schema@4.1.1)(@mastra/core@1.53.0(@cfworker/json-schema@4.1.1)(ai@6.0.303(zod@3.25.76))(express@5.3.0)(supports-color@10.2.2)(zod@3.25.76))(express@5.3.0)(hono@4.13.13)(zod@3.25.76)
484 + version: 1.17.2(@cfworker/json-schema@4.1.1)(@mastra/core@1.53.0(@cfworker/json-schema@4.1.1)(ai@6.0.303(zod@3.25.76))(express@5.3.0)(zod@3.25.76))(express@5.3.0)(hono@4.13.13)(zod@3.25.76)
485 ai:
486 specifier: ^6.0.302
487 version: 6.0.303(zod@3.25.76)
@@ -640,6 +640,28 @@ importers:
640 specifier: 'catalog:'
641 version: 7.0.2
642
643 + ts/examples/approvals:
644 + dependencies:
645 + '@composio/core':
646 + specifier: workspace:*
647 + version: link:../../packages/core
648 + '@modelcontextprotocol/sdk':
649 + specifier: 'catalog:'
650 + version: 1.32.1(@cfworker/json-schema@4.1.1)(zod@4.5.4)
651 + dotenv:
652 + specifier: 'catalog:'
653 + version: 18.0.7
654 + zod:
655 + specifier: 'catalog:'
656 + version: 4.5.4
657 + devDependencies:
658 + '@types/bun':
659 + specifier: 'catalog:'
660 + version: 1.4.3
661 + typescript:
662 + specifier: 'catalog:'
663 + version: 7.0.2
664 +
665 ts/examples/cloudflare-wrangler:
666 dependencies:
667 '@composio/core':
@@ -2731,12 +2753,6 @@ packages:
2753 '@modelcontextprotocol/sdk':
2754 optional: true
2755
2734 - '@hono/node-server@2.1.1':
2735 - resolution: {integrity: sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg==}
2736 - engines: {node: '>=20'}
2737 - peerDependencies:
2738 - hono: ^4
2739 -
2756 '@hono/node-server@2.1.4':
2757 resolution: {integrity: sha512-2g1qeHl4BduwDn6L8nkAvDrPUWPMlkQ//a5NhP/zIyaXKMjZNRV+cG9Csu+BiJFf6+68pqzjf4Hi5sJGKHuS1g==}
2758 engines: {node: '>=20'}
@@ -4676,10 +4692,6 @@ packages:
4692 resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}
4693 engines: {node: ^14.18.0 || >=16.10.0}
4694
4679 - content-disposition@1.1.0:
4680 - resolution: {integrity: sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==}
4681 - engines: {node: '>=18'}
4682 -
4695 content-disposition@2.0.1:
4696 resolution: {integrity: sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==}
4697 engines: {node: '>=18'}
@@ -4968,22 +4980,12 @@ packages:
4980 resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
4981 engines: {node: '>=12.0.0'}
4982
4971 - express-rate-limit@8.6.2:
4972 - resolution: {integrity: sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A==}
4973 - engines: {node: '>= 16'}
4974 - peerDependencies:
4975 - express: '>= 4.11'
4976 -
4983 express-rate-limit@8.7.1:
4984 resolution: {integrity: sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==}
4985 engines: {node: '>= 16'}
4986 peerDependencies:
4987 express: '>= 4.11'
4988
4983 - express@5.2.1:
4984 - resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==}
4985 - engines: {node: '>= 18'}
4986 -
4989 express@5.3.0:
4990 resolution: {integrity: sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==}
4991 engines: {node: '>= 18'}
@@ -5169,10 +5171,6 @@ packages:
5171 resolution: {integrity: sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==}
5172 engines: {node: '>=16.9.0'}
5173
5172 - hono@4.13.9:
5173 - resolution: {integrity: sha512-7dMkQmZoC4E6F7AtaQSPhlWAdnBti+j7rreMZl8QB4jFiEhP9TWbGWUMi8WYzBCgmgulxuvLQupKqo+Co6Omyg==}
5174 - engines: {node: '>=16.9.0'}
5175 -
5174 hookable@6.1.1:
5175 resolution: {integrity: sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ==}
5176
@@ -5252,10 +5250,6 @@ packages:
5250 inherits@2.0.4:
5251 resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
5252
5255 - ip-address@10.7.3:
5256 - resolution: {integrity: sha512-A1kdq/tSb5QjvKvAMgIoEvDBIgL7qaqVP/jkvSwYYRZ9iEzvPpopxp2wQfu3SuZRHtpHNxMn8Fs0bS+gf5Xmwg==}
5257 - engines: {node: '>= 12'}
5258 -
5253 ip-address@10.7.4:
5254 resolution: {integrity: sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==}
5255 engines: {node: '>= 12'}
@@ -5337,9 +5331,6 @@ packages:
5331 jose@6.2.12:
5332 resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==}
5333
5340 - jose@6.2.9:
5341 - resolution: {integrity: sha512-XrchZOFZUl/T3vTwRe8XK+cJrGtMF4th1ARnDfwbBXFKThGhlsxEE4Zu03AD/bjJSt/9jT/mxrOCkJWOg77aPA==}
5342 -
5334 jpeg-js@0.4.4:
5335 resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==}
5336
@@ -7952,10 +7943,6 @@ snapshots:
7943 - supports-color
7944 - utf-8-validate
7945
7955 - '@hono/node-server@2.1.1(hono@4.13.9)':
7956 - dependencies:
7957 - hono: 4.13.9
7958 -
7946 '@hono/node-server@2.1.4(hono@4.13.13)':
7947 dependencies:
7948 hono: 4.13.13
@@ -8386,7 +8373,7 @@ snapshots:
8373 tinyglobby: 0.2.17
8374 yaml: 2.9.0
8375
8389 - '@mastra/core@1.53.0(@cfworker/json-schema@4.1.1)(ai@6.0.303(zod@3.25.76))(express@5.3.0)(supports-color@10.2.2)(zod@3.25.76)':
8376 + '@mastra/core@1.53.0(@cfworker/json-schema@4.1.1)(ai@6.0.303(zod@3.25.76))(express@5.3.0)(zod@3.25.76)':
8377 dependencies:
8378 '@a2a-js/sdk': 0.3.14(express@5.3.0)
8379 '@ai-sdk/provider-utils-v5': '@ai-sdk/provider-utils@3.0.30(zod@3.25.76)'
@@ -8399,7 +8386,7 @@ snapshots:
8386 '@isaacs/ttlcache': 2.1.5
8387 '@lukeed/uuid': 2.0.1
8388 '@mastra/schema-compat': 1.3.4(zod@3.25.76)
8402 - '@modelcontextprotocol/sdk': 1.32.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@3.25.76)
8389 + '@modelcontextprotocol/sdk': 1.32.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)
8390 '@sindresorhus/slugify': 2.2.1
8391 '@standard-schema/spec': 1.1.0
8392 ajv: 8.20.0
@@ -8478,9 +8465,9 @@ snapshots:
8465 - supports-color
8466 - utf-8-validate
8467
8481 - '@mastra/mcp@1.17.2(@cfworker/json-schema@4.1.1)(@mastra/core@1.53.0(@cfworker/json-schema@4.1.1)(ai@6.0.303(zod@3.25.76))(express@5.3.0)(supports-color@10.2.2)(zod@3.25.76))(express@5.3.0)(hono@4.13.13)(zod@3.25.76)':
8468 + '@mastra/mcp@1.17.2(@cfworker/json-schema@4.1.1)(@mastra/core@1.53.0(@cfworker/json-schema@4.1.1)(ai@6.0.303(zod@3.25.76))(express@5.3.0)(zod@3.25.76))(express@5.3.0)(hono@4.13.13)(zod@3.25.76)':
8469 dependencies:
8483 - '@mastra/core': 1.53.0(@cfworker/json-schema@4.1.1)(ai@6.0.303(zod@3.25.76))(express@5.3.0)(supports-color@10.2.2)(zod@3.25.76)
8470 + '@mastra/core': 1.53.0(@cfworker/json-schema@4.1.1)(ai@6.0.303(zod@3.25.76))(express@5.3.0)(zod@3.25.76)
8471 '@modelcontextprotocol/client': 2.2.0
8472 '@modelcontextprotocol/core': 2.2.0
8473 '@modelcontextprotocol/ext-apps': 1.7.5(@modelcontextprotocol/sdk@1.32.1(@cfworker/json-schema@4.1.1)(zod@3.25.76))(zod@3.25.76)
@@ -8575,9 +8562,9 @@ snapshots:
8562 optionalDependencies:
8563 hono: 4.13.13
8564
8578 - '@modelcontextprotocol/sdk@1.32.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@3.25.76)':
8565 + '@modelcontextprotocol/sdk@1.32.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)':
8566 dependencies:
8580 - '@hono/node-server': 2.1.1(hono@4.13.9)
8567 + '@hono/node-server': 2.1.4(hono@4.13.13)
8568 ajv: 8.20.0
8569 ajv-formats: 3.0.1(ajv@8.20.0)
8570 content-type: 1.0.5
@@ -8585,10 +8572,10 @@ snapshots:
8572 cross-spawn: 7.0.6
8573 eventsource: 3.0.7
8574 eventsource-parser: 3.1.1
8588 - express: 5.2.1(supports-color@10.2.2)
8589 - express-rate-limit: 8.6.2(express@5.2.1(supports-color@10.2.2))(supports-color@10.2.2)
8590 - hono: 4.13.9
8591 - jose: 6.2.9
8575 + express: 5.3.0
8576 + express-rate-limit: 8.7.1(express@5.3.0)
8577 + hono: 4.13.13
8578 + jose: 6.2.12
8579 json-schema-typed: 8.0.2
8580 pkce-challenge: 5.0.1
8581 raw-body: 3.0.2
@@ -8601,7 +8588,7 @@ snapshots:
8588
8589 '@modelcontextprotocol/sdk@1.32.0(@cfworker/json-schema@4.1.1)(zod@4.5.4)':
8590 dependencies:
8604 - '@hono/node-server': 2.1.1(hono@4.13.9)
8591 + '@hono/node-server': 2.1.4(hono@4.13.13)
8592 ajv: 8.20.0
8593 ajv-formats: 3.0.1(ajv@8.20.0)
8594 content-type: 1.0.5
@@ -8609,10 +8596,10 @@ snapshots:
8596 cross-spawn: 7.0.6
8597 eventsource: 3.0.7
8598 eventsource-parser: 3.1.1
8612 - express: 5.2.1(supports-color@10.2.2)
8613 - express-rate-limit: 8.6.2(express@5.2.1(supports-color@10.2.2))(supports-color@10.2.2)
8614 - hono: 4.13.9
8615 - jose: 6.2.9
8599 + express: 5.3.0
8600 + express-rate-limit: 8.7.1(express@5.3.0)
8601 + hono: 4.13.13
8602 + jose: 6.2.12
8603 json-schema-typed: 8.0.2
8604 pkce-challenge: 5.0.1
8605 raw-body: 3.0.2
@@ -9795,8 +9782,6 @@ snapshots:
9782
9783 consola@3.4.2: {}
9784
9798 - content-disposition@1.1.0: {}
9799 -
9785 content-disposition@2.0.1: {}
9786
9787 content-type@1.0.5: {}
@@ -10057,14 +10042,6 @@ snapshots:
10042
10043 expect-type@1.4.0: {}
10044
10060 - express-rate-limit@8.6.2(express@5.2.1(supports-color@10.2.2))(supports-color@10.2.2):
10061 - dependencies:
10062 - debug: 4.4.3(supports-color@10.2.2)
10063 - express: 5.2.1(supports-color@10.2.2)
10064 - ip-address: 10.7.3
10065 - transitivePeerDependencies:
10066 - - supports-color
10067 -
10045 express-rate-limit@8.7.1(express@5.3.0):
10046 dependencies:
10047 debug: 4.4.3(supports-color@10.2.2)
@@ -10073,39 +10050,6 @@ snapshots:
10050 transitivePeerDependencies:
10051 - supports-color
10052
10076 - express@5.2.1(supports-color@10.2.2):
10077 - dependencies:
10078 - accepts: 2.0.0
10079 - body-parser: 2.3.0
10080 - content-disposition: 1.1.0
10081 - content-type: 1.0.5
10082 - cookie: 0.7.2
10083 - cookie-signature: 1.2.2
10084 - debug: 4.4.3(supports-color@10.2.2)
10085 - depd: 2.0.0
10086 - encodeurl: 2.0.0
10087 - escape-html: 1.0.3
10088 - etag: 1.8.1
10089 - finalhandler: 2.1.1
10090 - fresh: 2.0.0
10091 - http-errors: 2.0.1
10092 - merge-descriptors: 2.0.0
10093 - mime-types: 3.0.2
10094 - on-finished: 2.4.1
10095 - once: 1.4.0
10096 - parseurl: 1.3.3
10097 - proxy-addr: 2.0.8
10098 - qs: 6.16.0
10099 - range-parser: 1.3.0
10100 - router: 2.2.0
10101 - send: 1.2.1
10102 - serve-static: 2.2.1
10103 - statuses: 2.0.2
10104 - type-is: 2.1.0
10105 - vary: 1.1.2
10106 - transitivePeerDependencies:
10107 - - supports-color
10108 -
10053 express@5.3.0:
10054 dependencies:
10055 accepts: 2.0.0
@@ -10323,8 +10267,6 @@ snapshots:
10267
10268 hono@4.13.13: {}
10269
10326 - hono@4.13.9: {}
10327 -
10270 hookable@6.1.1: {}
10271
10272 hookable@6.1.2: {}
@@ -10407,8 +10349,6 @@ snapshots:
10349
10350 inherits@2.0.4: {}
10351
10410 - ip-address@10.7.3: {}
10411 -
10352 ip-address@10.7.4: {}
10353
10354 ipaddr.js@1.9.1: {}
@@ -10455,8 +10395,6 @@ snapshots:
10395
10396 jose@6.2.12: {}
10397
10458 - jose@6.2.9: {}
10459 -
10398 jpeg-js@0.4.4: {}
10399
10400 js-levenshtein@1.1.6: {}
python/examples/README.md
+6
@@ -32,3 +32,9 @@ Run `node ../scripts/examples-provision.mjs --gc` to delete what example runs le
32 ## A note on connection examples
33
34 `connected_accounts.py` demonstrates _creating_ a connection: it calls `initiate()`, prints `Visit this URL to authorize: ...`, then calls `wait_for_connection()`, which returns once the account is active or gives up after its default timeout. That wait needs a person to open the URL, so the example cannot finish on its own and automated runs skip it. Examples that _use_ a connection (calling a tool through Gmail, GitHub, or Slack) rely on the standing connected accounts that the provisioning script already verified are active.
35 +
36 +## Session approval examples
37 +
38 +Run `uv run --project python python python/examples/approvals.py` from the repository root to approve, deny, decline, or cancel a read-only Hacker News lookup. Add `--multi` to answer a batch of two calls. Set `COMPOSIO_API_KEY` first; no connected account or model API key is needed.
39 +
40 +See the [approval examples walkthrough](../../ts/examples/approvals/README.md) for setup, the MCP client, and CI coverage. `verify_approvals.py` runs the same helpers with fixed answers against staging in the scheduled manifest sweep.
python/examples/approvals.py new
+122
@@ -0,0 +1,122 @@
1 +"""Run a read-only tool (or --multi batch), asking for approval in the terminal."""
2 +
3 +import argparse
4 +import os
5 +import uuid
6 +from collections.abc import Callable
7 +from typing import TypeVar
8 +
9 +from composio import Composio
10 +from composio.core.models.tool_router_session import (
11 + ToolRouterInputResponse,
12 + ToolRouterSession,
13 +)
14 +from composio.exceptions import ToolInputRequest, ToolInputRequiredError
15 +from jsonschema import validate
16 +
17 +TOOL = "HACKERNEWS_GET_USER"
18 +APPROVAL_TOOLS = [TOOL, "HACKERNEWS_GET_MAX_ITEM_ID"]
19 +ARGUMENTS = {"username": "pg"}
20 +MULTI_ARGUMENTS = {
21 + "tools": [
22 + {"tool_slug": TOOL, "arguments": ARGUMENTS},
23 + {"tool_slug": "HACKERNEWS_GET_MAX_ITEM_ID", "arguments": {}},
24 + ],
25 + "sync_response_to_workbench": False,
26 +}
27 +T = TypeVar("T")
28 +
29 +
30 +def ask_for_approval(
31 + question: ToolInputRequest, read: Callable[[str], str] = input
32 +) -> ToolRouterInputResponse:
33 + """Support approval decision forms; a general UI should render the full schema."""
34 + if question["mode"] != "form":
35 + raise ValueError("This example supports form elicitation only")
36 + schema = question["requested_schema"]
37 + field = schema["properties"]["decision"]
38 + choices = [choice["const"] for choice in field.get("oneOf", [])] or field.get(
39 + "enum", []
40 + )
41 + if not choices:
42 + raise ValueError("Approval form has no decision choices")
43 + print(question["message"])
44 + while True:
45 + try:
46 + answer = read(f"Decision ({'/'.join(choices)}; decline/cancel): ").strip()
47 + except (EOFError, KeyboardInterrupt):
48 + return {"action": "cancel"}
49 + if answer == "decline":
50 + return {"action": "decline"}
51 + if answer == "cancel":
52 + return {"action": "cancel"}
53 + if answer in choices:
54 + content: dict[str, object | None] = {"decision": answer}
55 + validate(content, schema)
56 + return {"action": "accept", "content": content}
57 + print("Choose one of the displayed answers.")
58 +
59 +
60 +def run_with_approvals(
61 + execute: Callable[..., T],
62 + ask_user: Callable[[ToolInputRequest], ToolRouterInputResponse],
63 +) -> T:
64 + answers = {}
65 + while True:
66 + try:
67 + return execute(**answers)
68 + except ToolInputRequiredError as error:
69 + # Ask every question before resuming, preserving IDs and opaque state.
70 + responses = {
71 + question_id: ask_user(question)
72 + for question_id, question in error.input_requests.items()
73 + }
74 + answers = {
75 + "input_responses": responses,
76 + "request_state": error.request_state,
77 + }
78 +
79 +
80 +def create_composio() -> Composio:
81 + api_key = os.environ.get("COMPOSIO_API_KEY")
82 + if not api_key:
83 + raise RuntimeError("Set COMPOSIO_API_KEY before running this example")
84 + return Composio(api_key=api_key)
85 +
86 +
87 +def create_approval_session(composio: Composio) -> ToolRouterSession:
88 + return composio.create(
89 + user_id=f"approvals-example-{uuid.uuid4()}",
90 + toolkits=["hackernews"],
91 + tools={
92 + "hackernews": {"enable": APPROVAL_TOOLS, "require_approval": APPROVAL_TOOLS}
93 + },
94 + sandbox={"enable": False},
95 + )
96 +
97 +
98 +def main():
99 + parser = argparse.ArgumentParser(description=__doc__)
100 + parser.add_argument(
101 + "--multi", action="store_true", help="Ask about a batch of two tools"
102 + )
103 + args = parser.parse_args()
104 + composio = create_composio()
105 + session = create_approval_session(composio)
106 + try:
107 +
108 + def execute(**answers):
109 + if args.multi:
110 + return session.execute_meta(
111 + "COMPOSIO_MULTI_EXECUTE_TOOL", arguments=MULTI_ARGUMENTS, **answers
112 + )
113 + return session.execute(TOOL, arguments=ARGUMENTS, **answers)
114 +
115 + result = run_with_approvals(execute, ask_for_approval)
116 + print(result.model_dump_json(indent=2))
117 + finally:
118 + composio.sessions.delete(session.session_id)
119 +
120 +
121 +if __name__ == "__main__":
122 + main()
python/examples/verify_approvals.py new
+139
@@ -0,0 +1,139 @@
1 +"""Unattended CI checks, restricted to the read-only tools from approvals.py."""
2 +
3 +import re
4 +
5 +from approvals import (
6 + ARGUMENTS,
7 + MULTI_ARGUMENTS,
8 + TOOL,
9 + create_approval_session,
10 + create_composio,
11 + run_with_approvals,
12 +)
13 +from pydantic import BaseModel, TypeAdapter
14 +
15 +
16 +class ToolResponse(BaseModel):
17 + successful: bool
18 + error: str | None = None
19 +
20 +
21 +class BatchItem(BaseModel):
22 + error: str | None = None
23 + response: ToolResponse | None = None
24 +
25 +
26 +class Batch(BaseModel):
27 + results: list[BatchItem]
28 + total_count: int
29 + success_count: int
30 + error_count: int
31 +
32 +
33 +class BatchWrapper(BaseModel):
34 + data: Batch
35 +
36 +
37 +def assert_batch(data: dict[str, object], successes: int, failures: int) -> None:
38 + parsed = TypeAdapter(Batch | BatchWrapper).validate_python(data)
39 + batch = parsed.data if isinstance(parsed, BatchWrapper) else parsed
40 + assert batch.total_count == successes + failures
41 + assert len(batch.results) == successes + failures
42 + assert batch.success_count == successes
43 + assert batch.error_count == failures
44 + denied = 0
45 + for item in batch.results:
46 + error = item.error or (item.response.error if item.response else None)
47 + if error:
48 + assert re.search(r"approv|deni|declin|cancel|reject", error, re.I)
49 + denied += 1
50 + else:
51 + assert item.response is not None and item.response.successful
52 + assert denied == failures
53 +
54 +
55 +def main():
56 + composio = create_composio()
57 + cases = [
58 + ("approve", {"action": "accept", "content": {"decision": "approve"}}, True),
59 + ("deny", {"action": "accept", "content": {"decision": "deny"}}, False),
60 + ("decline", {"action": "decline"}, False),
61 + ("cancel", {"action": "cancel"}, False),
62 + (
63 + "always_approve",
64 + {"action": "accept", "content": {"decision": "always_approve"}},
65 + True,
66 + ),
67 + ]
68 + for label, answer, allowed in cases:
69 + session = create_approval_session(composio)
70 + try:
71 + prompts = 0
72 +
73 + def ask_user(question):
74 + nonlocal prompts
75 + prompts += 1
76 + assert prompts <= 2, "Approval did not resolve"
77 + return answer
78 +
79 + result = run_with_approvals(
80 + lambda **answers: session.execute(TOOL, arguments=ARGUMENTS, **answers),
81 + ask_user,
82 + )
83 + assert prompts > 0, "Execution bypassed approval"
84 + assert result.result_type == ("completed" if allowed else "failed")
85 + if allowed:
86 + assert result.error is None
87 + assert result.data
88 + else:
89 + assert re.search(
90 + r"approv|deni|declin|cancel|reject", str(result.error), re.I
91 + )
92 + if label == "always_approve":
93 +
94 + def must_not_ask(question):
95 + raise AssertionError(
96 + "Always approve asked again in the same session"
97 + )
98 +
99 + next_result = run_with_approvals(
100 + lambda **answers: session.execute(
101 + TOOL, arguments={"username": "dang"}, **answers
102 + ),
103 + must_not_ask,
104 + )
105 + assert next_result.result_type == "completed"
106 + assert next_result.error is None
107 + assert next_result.data
108 + print(f"PASS {label}")
109 + finally:
110 + composio.sessions.delete(session.session_id)
111 +
112 + session = create_approval_session(composio)
113 + try:
114 + prompts = 0
115 +
116 + def ask_batch(question):
117 + nonlocal prompts
118 + prompts += 1
119 + assert prompts <= 2, "Batch approval did not resolve"
120 + return {
121 + "action": "accept",
122 + "content": {"decision": "approve" if prompts == 1 else "deny"},
123 + }
124 +
125 + result = run_with_approvals(
126 + lambda **answers: session.execute_meta(
127 + "COMPOSIO_MULTI_EXECUTE_TOOL", arguments=MULTI_ARGUMENTS, **answers
128 + ),
129 + ask_batch,
130 + )
131 + assert prompts == 2, "Expected a question for each tool call"
132 + assert_batch(result.data, 1, 1)
133 + print("PASS batch with one approval and one denial")
134 + finally:
135 + composio.sessions.delete(session.session_id)
136 +
137 +
138 +if __name__ == "__main__":
139 + main()
python/tests/test_approval_examples.py new
+122
@@ -0,0 +1,122 @@
1 +"""Exercise the same approval helpers used by the runnable examples."""
2 +
3 +import pytest
4 +from composio.exceptions import ToolInputRequiredError
5 +from examples.approvals import ask_for_approval, run_with_approvals
6 +
7 +QUESTION = {
8 + "type": "elicitation",
9 + "mode": "form",
10 + "message": "Allow this read-only call?",
11 + "requested_schema": {
12 + "type": "object",
13 + "properties": {
14 + "decision": {
15 + "type": "string",
16 + "oneOf": [
17 + {"const": "approve"},
18 + {"const": "always_approve"},
19 + {"const": "deny"},
20 + ],
21 + }
22 + },
23 + "required": ["decision"],
24 + },
25 +}
26 +
27 +
28 +@pytest.mark.parametrize(
29 + "choice", ["approve", "always_approve", "deny", "decline", "cancel"]
30 +)
31 +def test_forwards_the_persons_choice(choice):
32 + response = ask_for_approval(QUESTION, lambda _: choice)
33 + assert response == (
34 + {"action": choice}
35 + if choice in ("decline", "cancel")
36 + else {"action": "accept", "content": {"decision": choice}}
37 + )
38 +
39 +
40 +def test_invalid_choice_is_not_submitted():
41 + answers = iter(["yes", "approve"])
42 + assert ask_for_approval(QUESTION, lambda _: next(answers)) == {
43 + "action": "accept",
44 + "content": {"decision": "approve"},
45 + }
46 + assert list(answers) == []
47 +
48 +
49 +@pytest.mark.parametrize("error", [EOFError, KeyboardInterrupt])
50 +def test_closed_terminal_cancels(error):
51 + def closed(_):
52 + raise error()
53 +
54 + assert ask_for_approval(QUESTION, closed) == {"action": "cancel"}
55 +
56 +
57 +def test_all_batch_answers_and_new_continuation_state_are_forwarded():
58 + calls = []
59 + answers = iter(
60 + [
61 + {"action": "accept", "content": {"decision": "approve"}},
62 + {"action": "decline"},
63 + {"action": "cancel"},
64 + ]
65 + )
66 +
67 + def execute(**options):
68 + calls.append(options)
69 + if len(calls) == 1:
70 + raise ToolInputRequiredError(
71 + "Batch",
72 + input_requests={"first": QUESTION, "second": QUESTION},
73 + request_state="first-state",
74 + )
75 + if len(calls) == 2:
76 + assert options == {
77 + "input_responses": {
78 + "first": {"action": "accept", "content": {"decision": "approve"}},
79 + "second": {"action": "decline"},
80 + },
81 + "request_state": "first-state",
82 + }
83 + raise ToolInputRequiredError(
84 + "Batch", input_requests={"next": QUESTION}, request_state="next-state"
85 + )
86 + assert options == {
87 + "input_responses": {"next": {"action": "cancel"}},
88 + "request_state": "next-state",
89 + }
90 + return "done"
91 +
92 + assert run_with_approvals(execute, lambda _: next(answers)) == "done"
93 + assert len(calls) == 3
94 +
95 +
96 +def test_waits_for_the_person_before_resuming():
97 + calls = []
98 +
99 + def execute(**options):
100 + calls.append(options)
101 + if not options:
102 + raise ToolInputRequiredError("Read", input_requests={"id": QUESTION})
103 + return "cancelled"
104 +
105 + def ask_user(_):
106 + assert calls == [{}]
107 + return {"action": "cancel"}
108 +
109 + assert run_with_approvals(execute, ask_user) == "cancelled"
110 + assert calls[1]["input_responses"] == {"id": {"action": "cancel"}}
111 +
112 +
113 +def test_execution_failure_is_not_retried():
114 + calls = []
115 +
116 + def execute(**options):
117 + calls.append(options)
118 + raise RuntimeError("network failure")
119 +
120 + with pytest.raises(RuntimeError, match="network failure"):
121 + run_with_approvals(execute, lambda _: pytest.fail("must not ask"))
122 + assert calls == [{}]
ts/examples/approvals/README.md new
+87
@@ -0,0 +1,87 @@
1 +# Session approvals
2 +
3 +Ask before running a tool, then resume the same call with your answer. These examples use read-only Hacker News lookups so you can try every choice without a connected account or model API key.
4 +
5 +From the repository root, install dependencies and build the SDK:
6 +
7 +```bash
8 +pnpm install
9 +pnpm exec turbo build --filter=@composio/core
10 +export COMPOSIO_API_KEY=your_project_key
11 +pnpm --filter approvals-example start
12 +```
13 +
14 +To use staging, also set `COMPOSIO_BASE_URL=https://staging-backend.composio.dev`. Otherwise the SDK uses production.
15 +
16 +## Choose an answer
17 +
18 +The terminal prints the tool call and reads the decision choices from the returned schema. Enter `approve`, `always_approve`, or `deny` when offered. You can also enter `decline` or `cancel` to return those MCP elicitation actions without form content. An invalid choice asks again.
19 +
20 +`deny` is a submitted form decision (`action: 'accept'`, `content: { decision: 'deny' }`). `decline` and `cancel` are protocol actions. All three are forwarded unchanged, and Composio decides the execution result. `always_approve` applies to that tool and connected account for the rest of the Session.
21 +
22 +[`approval.ts`](src/approval.ts) waits for every answer before repeating the original call with `inputResponses` and the opaque `requestState`. It handles another input request if needed and propagates other execution errors. This terminal UI supports approval decision forms. Build a complete schema renderer for other elicitation forms.
23 +
24 +## Run the Python version
25 +
26 +```bash
27 +uv sync --project python --frozen
28 +uv run --project python python python/examples/approvals.py
29 +```
30 +
31 +The [Python example](../../../python/examples/approvals.py) uses the same flow with `input_responses` and `request_state`. Closing its terminal prompt returns `cancel`.
32 +
33 +## Answer several questions
34 +
35 +```bash
36 +pnpm --filter approvals-example start:multi
37 +uv run --project python python python/examples/approvals.py --multi
38 +```
39 +
40 +These calls use `session.executeMeta()` / `session.execute_meta()` with `COMPOSIO_MULTI_EXECUTE_TOOL` to look up a Hacker News user and the latest item ID. Try approving one and denying the other. The helpers collect every returned question by ID before resuming the batch. Inspect each tool's result; a completed meta-tool response can contain denied or failed app-tool calls.
41 +
42 +## Connect an MCP client
43 +
44 +```bash
45 +pnpm --filter approvals-example start:mcp
46 +```
47 +
48 +[`mcp.ts`](src/mcp.ts) creates a Session with `mcp: true`, connects with `session.mcp.url` and `session.mcp.headers`, advertises form elicitation, and registers an `elicitation/create` handler. The handler uses the same terminal prompt. The client calls `COMPOSIO_MULTI_EXECUTE_TOOL` and Composio asks for input over MCP; your application doesn't resubmit an SDK call.
49 +
50 +To try a client without elicitation support:
51 +
52 +```bash
53 +pnpm --filter approvals-example exec bun src/mcp.ts --no-elicitation
54 +```
55 +
56 +The example explicitly sets `noElicitationSupportFallback: 'deny'`. The calls are denied without a prompt. Keep this fallback when approval is required. Clients such as Claude Code supply their own elicitation UI; this example shows how to implement that part in your own client.
57 +
58 +## CI coverage
59 +
60 +Pull requests run the terminal and continuation tests in `.github/workflows/ts.examples.yml` and `.github/workflows/py.test.yml`. The TypeScript tests also connect the actual example MCP client to an in-memory MCP server and check answer forwarding and capability negotiation. These tests need no credentials.
61 +
62 +Run them locally:
63 +
64 +```bash
65 +pnpm --filter approvals-example test
66 +uv run --project python pytest python/tests/test_approval_examples.py
67 +```
68 +
69 +The existing staging manifest sweep runs three unattended entries nightly and on demand:
70 +
71 +| Manifest entry | Backend assertions |
72 +| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
73 +| `ts/approvals/verify` | Approval is requested; approve succeeds; deny, decline, and cancel fail for approval reasons; Always approve suppresses the next prompt; a mixed batch has one success and one denial. |
74 +| `py/approvals/verify` | The same assertions through the Python SDK. |
75 +| `ts/approvals/verify-mcp` | An elicitation-capable client receives questions and runs the tools; a client without elicitation is denied. |
76 +
77 +Run just those entries against a disposable staging project:
78 +
79 +```bash
80 +COMPOSIO_BASE_URL=https://staging-backend.composio.dev \
81 + node harness/run.mjs sweep --llm mock \
82 + --ids ts/approvals/verify,py/approvals/verify,ts/approvals/verify-mcp
83 +```
84 +
85 +The verification scripts supply fixed answers only for the explicitly gated read-only tools in this example. Keep human input in application flows. Each script creates fresh Sessions, fails if approval was skipped, and deletes its Sessions in `finally`. The interactive entrypoints are excluded from unattended sweeps so CI never waits for terminal input. Missing credentials fail verification; they don't count as passing coverage.
86 +
87 +See the [approvals guide](https://docs.composio.dev/docs/approvals) for configuration and current limitations.
ts/examples/approvals/package.json new
+26
@@ -0,0 +1,26 @@
1 +{
2 + "name": "approvals-example",
3 + "private": true,
4 + "version": "0.0.0",
5 + "type": "module",
6 + "scripts": {
7 + "start": "bun src/index.ts",
8 + "start:multi": "bun src/index.ts --multi",
9 + "start:mcp": "bun src/mcp.ts",
10 + "verify": "bun src/verify.ts",
11 + "verify:mcp": "bun src/verify-mcp.ts",
12 + "test": "bun test test/",
13 + "typecheck": "tsc --noEmit -p tsconfig.json",
14 + "lint": "oxlint src test"
15 + },
16 + "dependencies": {
17 + "@composio/core": "workspace:*",
18 + "@modelcontextprotocol/sdk": "catalog:",
19 + "dotenv": "catalog:",
20 + "zod": "catalog:"
21 + },
22 + "devDependencies": {
23 + "@types/bun": "catalog:",
24 + "typescript": "catalog:"
25 + }
26 +}
ts/examples/approvals/src/approval.ts new
+61
@@ -0,0 +1,61 @@
1 +import {
2 + ComposioToolInputRequiredError,
3 + type ToolRouterInputRequest,
4 + type ToolRouterInputResponse,
5 + type ToolRouterSessionExecuteOptions,
6 +} from '@composio/core';
7 +import { z } from 'zod';
8 +
9 +export type AskUser = (question: ToolRouterInputRequest) => Promise<ToolRouterInputResponse>;
10 +
11 +// This terminal example supports the decision forms used for tool approvals.
12 +// A general elicitation UI should render and validate the whole JSON Schema.
13 +const approvalSchema = z.object({
14 + type: z.literal('object'),
15 + properties: z.object({
16 + decision: z.object({
17 + type: z.literal('string'),
18 + oneOf: z.array(z.object({ const: z.string(), title: z.string().optional() })).optional(),
19 + enum: z.array(z.string()).optional(),
20 + }),
21 + }),
22 +});
23 +
24 +export async function askForApproval(
25 + question: ToolRouterInputRequest,
26 + read: (prompt: string) => Promise<string>,
27 + show: (message: string) => void = console.log
28 +): Promise<ToolRouterInputResponse> {
29 + if (question.mode !== 'form') throw new Error('This example supports form elicitation only');
30 + const schema = approvalSchema.parse(question.requestedSchema);
31 + const field = schema.properties.decision;
32 + const choices = field.oneOf?.map(choice => choice.const) ?? field.enum ?? [];
33 + if (choices.length === 0) throw new Error('Approval form has no decision choices');
34 + show(question.message);
35 + while (true) {
36 + const answer = (await read(`Decision (${choices.join('/')}; decline/cancel): `)).trim();
37 + if (answer === 'decline' || answer === 'cancel') return { action: answer };
38 + if (choices.includes(answer)) return { action: 'accept', content: { decision: answer } };
39 + show('Choose one of the displayed answers.');
40 + }
41 +}
42 +
43 +export async function runWithApprovals<T>(
44 + execute: (options: ToolRouterSessionExecuteOptions) => Promise<T>,
45 + askUser: AskUser
46 +): Promise<T> {
47 + let answers: ToolRouterSessionExecuteOptions = {};
48 + while (true) {
49 + try {
50 + return await execute(answers);
51 + } catch (error) {
52 + // Only input-required responses may resume. Other errors must reach the caller.
53 + if (!(error instanceof ComposioToolInputRequiredError)) throw error;
54 + const inputResponses: NonNullable<ToolRouterSessionExecuteOptions['inputResponses']> = {};
55 + for (const [id, question] of Object.entries(error.inputRequests)) {
56 + inputResponses[id] = await askUser(question);
57 + }
58 + answers = { inputResponses, requestState: error.requestState };
59 + }
60 + }
61 +}
ts/examples/approvals/src/index.ts new
+26
@@ -0,0 +1,26 @@
1 +import * as readline from 'node:readline/promises';
2 +import { askForApproval, runWithApprovals } from './approval';
3 +import {
4 + createApprovalSession,
5 + createComposio,
6 + multiArguments,
7 + tool,
8 + toolArguments,
9 +} from './session';
10 +
11 +const composio = createComposio();
12 +const session = await createApprovalSession(composio);
13 +const terminal = readline.createInterface({ input: process.stdin, output: process.stdout });
14 +try {
15 + const result = await runWithApprovals(
16 + options =>
17 + process.argv.includes('--multi')
18 + ? session.executeMeta('COMPOSIO_MULTI_EXECUTE_TOOL', multiArguments, options)
19 + : session.execute(tool, toolArguments, options),
20 + question => askForApproval(question, prompt => terminal.question(prompt))
21 + );
22 + console.log(JSON.stringify(result, null, 2));
23 +} finally {
24 + terminal.close();
25 + await composio.sessions.delete(session.sessionId);
26 +}
ts/examples/approvals/src/mcp-client.ts new
+23
@@ -0,0 +1,23 @@
1 +import { Client } from '@modelcontextprotocol/sdk/client/index.js';
2 +import { ElicitRequestSchema } from '@modelcontextprotocol/sdk/types.js';
3 +import { type AskUser } from './approval';
4 +
5 +export function createApprovalClient(askUser?: AskUser) {
6 + const client = new Client(
7 + { name: 'composio-approvals-example', version: '1.0.0' },
8 + { capabilities: askUser ? { elicitation: { form: {} } } : {} }
9 + );
10 + if (askUser) {
11 + client.setRequestHandler(ElicitRequestSchema, async request => {
12 + if (request.params.mode === 'url')
13 + throw new Error('This example supports form elicitation only');
14 + return askUser({
15 + type: 'elicitation',
16 + mode: 'form',
17 + message: request.params.message,
18 + requestedSchema: request.params.requestedSchema,
19 + });
20 + });
21 + }
22 + return client;
23 +}
ts/examples/approvals/src/mcp.ts new
+40
@@ -0,0 +1,40 @@
1 +import * as readline from 'node:readline/promises';
2 +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
3 +import { askForApproval } from './approval';
4 +import { createApprovalClient } from './mcp-client';
5 +import { approvalTools, createComposio, multiArguments } from './session';
6 +
7 +const composio = createComposio();
8 +const session = await composio.create(`approvals-mcp-${crypto.randomUUID()}`, {
9 + mcp: true,
10 + toolkits: ['hackernews'],
11 + tools: { hackernews: { enable: approvalTools, requireApproval: approvalTools } },
12 + sandbox: { enable: false },
13 + experimental: { noElicitationSupportFallback: 'deny' },
14 +});
15 +const terminal = readline.createInterface({ input: process.stdin, output: process.stdout });
16 +// Omit the handler and capability to demonstrate the deny fallback.
17 +const client = createApprovalClient(
18 + process.argv.includes('--no-elicitation')
19 + ? undefined
20 + : question => askForApproval(question, prompt => terminal.question(prompt))
21 +);
22 +try {
23 + await client.connect(
24 + new StreamableHTTPClientTransport(new URL(session.mcp.url), {
25 + requestInit: { headers: session.mcp.headers },
26 + })
27 + );
28 + const result = await client.callTool({
29 + name: 'COMPOSIO_MULTI_EXECUTE_TOOL',
30 + arguments: multiArguments,
31 + });
32 + console.log(JSON.stringify(result, null, 2));
33 +} finally {
34 + terminal.close();
35 + try {
36 + await client.close();
37 + } finally {
38 + await composio.sessions.delete(session.sessionId);
39 + }
40 +}
ts/examples/approvals/src/session.ts new
+27
@@ -0,0 +1,27 @@
1 +import { Composio } from '@composio/core';
2 +import 'dotenv/config';
3 +
4 +export const tool = 'HACKERNEWS_GET_USER';
5 +export const approvalTools = [tool, 'HACKERNEWS_GET_MAX_ITEM_ID'];
6 +export const toolArguments = { username: 'pg' };
7 +export const multiArguments = {
8 + tools: [
9 + { tool_slug: tool, arguments: toolArguments },
10 + { tool_slug: 'HACKERNEWS_GET_MAX_ITEM_ID', arguments: {} },
11 + ],
12 + sync_response_to_workbench: false,
13 +};
14 +
15 +export function createComposio() {
16 + const apiKey = process.env.COMPOSIO_API_KEY;
17 + if (!apiKey) throw new Error('Set COMPOSIO_API_KEY before running this example');
18 + return new Composio({ apiKey, baseURL: process.env.COMPOSIO_BASE_URL });
19 +}
20 +
21 +export async function createApprovalSession(composio: Composio) {
22 + return composio.create(`approvals-example-${crypto.randomUUID()}`, {
23 + toolkits: ['hackernews'],
24 + tools: { hackernews: { enable: approvalTools, requireApproval: approvalTools } },
25 + sandbox: { enable: false },
26 + });
27 +}
ts/examples/approvals/src/verification.ts new
+42
@@ -0,0 +1,42 @@
1 +import assert from 'node:assert/strict';
2 +import { z } from 'zod';
3 +
4 +const batchSchema = z.object({
5 + results: z.array(
6 + z.object({
7 + error: z.string().nullish(),
8 + response: z.object({ successful: z.boolean(), error: z.string().nullish() }).nullish(),
9 + })
10 + ),
11 + total_count: z.number(),
12 + success_count: z.number(),
13 + error_count: z.number(),
14 +});
15 +// Session execution returns the tool data; MCP returns the tool's response wrapper.
16 +const batchResponseSchema = z.union([
17 + batchSchema,
18 + z.object({ data: batchSchema }).transform(wrapper => wrapper.data),
19 +]);
20 +
21 +export function assertBatch(data: unknown, successes: number, failures: number) {
22 + const batch = batchResponseSchema.parse(data);
23 + assert.equal(batch.total_count, successes + failures);
24 + assert.equal(batch.results.length, successes + failures);
25 + assert.equal(batch.success_count, successes);
26 + assert.equal(batch.error_count, failures);
27 + let denied = 0;
28 + for (const result of batch.results) {
29 + const error = result.error ?? result.response?.error;
30 + if (error) {
31 + assertDenied(error);
32 + denied++;
33 + } else {
34 + assert.ok(result.response?.successful, 'Tool did not succeed and has no approval denial');
35 + }
36 + }
37 + assert.equal(denied, failures);
38 +}
39 +
40 +export function assertDenied(error: unknown) {
41 + assert.match(JSON.stringify(error), /approv|deni|declin|cancel|reject/i);
42 +}
ts/examples/approvals/src/verify-mcp.ts new
+58
@@ -0,0 +1,58 @@
1 +/** Run the actual MCP example client against staging without a model. */
2 +import assert from 'node:assert/strict';
3 +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
4 +import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
5 +import { createApprovalClient } from './mcp-client';
6 +import { approvalTools, createComposio, multiArguments } from './session';
7 +import { assertBatch, assertDenied } from './verification';
8 +
9 +const composio = createComposio();
10 +for (const elicitation of [true, false]) {
11 + const session = await composio.create(`approvals-mcp-ci-${crypto.randomUUID()}`, {
12 + mcp: true,
13 + toolkits: ['hackernews'],
14 + tools: { hackernews: { enable: approvalTools, requireApproval: approvalTools } },
15 + sandbox: { enable: false },
16 + experimental: { noElicitationSupportFallback: 'deny' },
17 + });
18 + let prompts = 0;
19 + const client = createApprovalClient(
20 + elicitation
21 + ? async () => {
22 + assert.ok(++prompts <= 2, 'MCP approval did not resolve');
23 + return { action: 'accept', content: { decision: 'approve' } };
24 + }
25 + : undefined
26 + );
27 + try {
28 + await client.connect(
29 + new StreamableHTTPClientTransport(new URL(session.mcp.url), {
30 + requestInit: { headers: session.mcp.headers },
31 + })
32 + );
33 + const result = CallToolResultSchema.parse(
34 + await client.callTool({ name: 'COMPOSIO_MULTI_EXECUTE_TOOL', arguments: multiArguments })
35 + );
36 + assert.equal(prompts, elicitation ? 2 : 0);
37 + const text = result.content
38 + .filter(block => block.type === 'text')
39 + .map(block => block.text)
40 + .join('\n');
41 + if (!elicitation && result.isError) {
42 + assertDenied(text);
43 + } else {
44 + assertBatch(
45 + result.structuredContent ?? JSON.parse(text),
46 + elicitation ? 2 : 0,
47 + elicitation ? 0 : 2
48 + );
49 + }
50 + console.log(`PASS MCP ${elicitation ? 'elicitation' : 'deny fallback'}`);
51 + } finally {
52 + try {
53 + await client.close();
54 + } finally {
55 + await composio.sessions.delete(session.sessionId);
56 + }
57 + }
58 +}
ts/examples/approvals/src/verify.ts new
+73
@@ -0,0 +1,73 @@
1 +/** Unattended CI verification, restricted to the read-only tools in session.ts. */
2 +import assert from 'node:assert/strict';
3 +import { type ToolRouterInputResponse } from '@composio/core';
4 +import { runWithApprovals } from './approval';
5 +import {
6 + createApprovalSession,
7 + createComposio,
8 + multiArguments,
9 + tool,
10 + toolArguments,
11 +} from './session';
12 +import { assertBatch, assertDenied } from './verification';
13 +
14 +const composio = createComposio();
15 +const cases: [string, ToolRouterInputResponse, boolean][] = [
16 + ['approve', { action: 'accept', content: { decision: 'approve' } }, true],
17 + ['deny', { action: 'accept', content: { decision: 'deny' } }, false],
18 + ['decline', { action: 'decline' }, false],
19 + ['cancel', { action: 'cancel' }, false],
20 + ['always_approve', { action: 'accept', content: { decision: 'always_approve' } }, true],
21 +];
22 +
23 +for (const [label, answer, allowed] of cases) {
24 + // Fresh sessions prevent Always approve from affecting other cases.
25 + const session = await createApprovalSession(composio);
26 + try {
27 + let prompts = 0;
28 + const result = await runWithApprovals(
29 + options => session.execute(tool, toolArguments, options),
30 + async () => {
31 + assert.ok(++prompts <= 2, 'Approval did not resolve');
32 + return answer;
33 + }
34 + );
35 + assert.ok(prompts > 0, 'Execution bypassed approval');
36 + assert.equal(result.resultType, allowed ? 'completed' : 'failed');
37 + if (allowed) {
38 + assert.equal(result.error, null);
39 + assert.ok(Object.keys(result.data).length > 0);
40 + } else assertDenied(result.error);
41 + if (label === 'always_approve') {
42 + const next = await runWithApprovals(
43 + options => session.execute(tool, { username: 'dang' }, options),
44 + async () => {
45 + throw new Error('Always approve asked again in the same session');
46 + }
47 + );
48 + assert.equal(next.resultType, 'completed');
49 + assert.equal(next.error, null);
50 + assert.ok(Object.keys(next.data).length > 0);
51 + }
52 + console.log(`PASS ${label}`);
53 + } finally {
54 + await composio.sessions.delete(session.sessionId);
55 + }
56 +}
57 +
58 +const session = await createApprovalSession(composio);
59 +try {
60 + let prompts = 0;
61 + const result = await runWithApprovals(
62 + options => session.executeMeta('COMPOSIO_MULTI_EXECUTE_TOOL', multiArguments, options),
63 + async () => {
64 + assert.ok(++prompts <= 2, 'Batch approval did not resolve');
65 + return { action: 'accept', content: { decision: prompts === 1 ? 'approve' : 'deny' } };
66 + }
67 + );
68 + assert.equal(prompts, 2, 'Expected a question for each tool call');
69 + assertBatch(result.data, 1, 1);
70 + console.log('PASS batch with one approval and one denial');
71 +} finally {
72 + await composio.sessions.delete(session.sessionId);
73 +}
ts/examples/approvals/test/approval.test.ts new
+198
@@ -0,0 +1,198 @@
1 +import { describe, expect, test } from 'bun:test';
2 +import {
3 + ComposioToolInputRequiredError,
4 + type ToolRouterInputRequest,
5 + type ToolRouterInputResponse,
6 +} from '@composio/core';
7 +import { askForApproval, runWithApprovals } from '../src/approval';
8 +import { assertBatch } from '../src/verification';
9 +
10 +const question: ToolRouterInputRequest = {
11 + type: 'elicitation',
12 + mode: 'form',
13 + message: 'Allow this read-only call?',
14 + requestedSchema: {
15 + type: 'object',
16 + properties: {
17 + decision: {
18 + type: 'string',
19 + oneOf: [{ const: 'approve' }, { const: 'always_approve' }, { const: 'deny' }],
20 + },
21 + },
22 + required: ['decision'],
23 + },
24 +};
25 +
26 +describe('terminal approvals', () => {
27 + test.each(['approve', 'always_approve', 'deny', 'decline', 'cancel'])(
28 + 'forwards the person’s %s choice',
29 + async choice => {
30 + const response = await askForApproval(
31 + question,
32 + async () => choice,
33 + () => {}
34 + );
35 + expect(response).toEqual(
36 + choice === 'decline' || choice === 'cancel'
37 + ? { action: choice }
38 + : { action: 'accept', content: { decision: choice } }
39 + );
40 + }
41 + );
42 +
43 + test('rejects an invalid choice and asks again', async () => {
44 + const answers = ['yes', 'approve'];
45 + let reads = 0;
46 + expect(
47 + await askForApproval(
48 + question,
49 + async () => answers[reads++],
50 + () => {}
51 + )
52 + ).toEqual({ action: 'accept', content: { decision: 'approve' } });
53 + expect(reads).toBe(2);
54 + });
55 +
56 + test('uses the schema choices instead of adding Always approve', async () => {
57 + const answers = ['always_approve', 'deny'];
58 + const restricted = {
59 + ...question,
60 + requestedSchema: {
61 + type: 'object',
62 + properties: { decision: { type: 'string', enum: ['approve', 'deny'] } },
63 + },
64 + };
65 + let reads = 0;
66 + expect(
67 + await askForApproval(
68 + restricted,
69 + async () => answers[reads++],
70 + () => {}
71 + )
72 + ).toEqual({ action: 'accept', content: { decision: 'deny' } });
73 + expect(reads).toBe(2);
74 + });
75 +});
76 +
77 +test('waits for consent before resuming the call', async () => {
78 + let release!: (answer: ToolRouterInputResponse) => void;
79 + const consent = new Promise<ToolRouterInputResponse>(resolve => {
80 + release = resolve;
81 + });
82 + let calls = 0;
83 + const pending = runWithApprovals(
84 + async options => {
85 + calls++;
86 + if (!options.inputResponses)
87 + throw new ComposioToolInputRequiredError('Read', {
88 + inputRequests: { random_id: question },
89 + requestState: 'opaque-token',
90 + });
91 + expect(options).toEqual({
92 + inputResponses: { random_id: { action: 'cancel' } },
93 + requestState: 'opaque-token',
94 + });
95 + return 'cancelled';
96 + },
97 + () => consent
98 + );
99 + await Promise.resolve();
100 + await Promise.resolve();
101 + expect(calls).toBe(1);
102 + release({ action: 'cancel' });
103 + expect(await pending).toBe('cancelled');
104 + expect(calls).toBe(2);
105 +});
106 +
107 +test('answers all batch questions and replaces continuation state on another round', async () => {
108 + const responses: ToolRouterInputResponse[] = [
109 + { action: 'accept', content: { decision: 'approve' } },
110 + { action: 'decline' },
111 + { action: 'cancel' },
112 + ];
113 + let calls = 0;
114 + let answerIndex = 0;
115 + const result = await runWithApprovals(
116 + async options => {
117 + calls++;
118 + if (calls === 1)
119 + throw new ComposioToolInputRequiredError('Batch', {
120 + inputRequests: { first: question, second: question },
121 + requestState: 'first-state',
122 + });
123 + if (calls === 2) {
124 + expect(options).toEqual({
125 + inputResponses: { first: responses[0], second: responses[1] },
126 + requestState: 'first-state',
127 + });
128 + throw new ComposioToolInputRequiredError('Batch', {
129 + inputRequests: { next: question },
130 + requestState: 'next-state',
131 + });
132 + }
133 + expect(options).toEqual({
134 + inputResponses: { next: responses[2] },
135 + requestState: 'next-state',
136 + });
137 + return 'done';
138 + },
139 + async () => responses[answerIndex++]
140 + );
141 + expect(result).toBe('done');
142 +});
143 +
144 +test('propagates execution and UI failures without retrying', async () => {
145 + let calls = 0;
146 + await expect(
147 + runWithApprovals(
148 + async () => {
149 + calls++;
150 + throw new Error('network failure');
151 + },
152 + async () => {
153 + throw new Error('must not ask');
154 + }
155 + )
156 + ).rejects.toThrow('network failure');
157 + expect(calls).toBe(1);
158 + await expect(
159 + runWithApprovals(
160 + async () => {
161 + throw new ComposioToolInputRequiredError('Read', { inputRequests: { first: question } });
162 + },
163 + async () => {
164 + throw new Error('UI failed');
165 + }
166 + )
167 + ).rejects.toThrow('UI failed');
168 +});
169 +
170 +test('live verification rejects a completed batch with failed inner calls', () => {
171 + expect(() =>
172 + assertBatch(
173 + {
174 + total_count: 2,
175 + success_count: 0,
176 + error_count: 2,
177 + results: [{ error: 'upstream unavailable' }, { error: 'upstream unavailable' }],
178 + },
179 + 2,
180 + 0
181 + )
182 + ).toThrow();
183 +});
184 +
185 +test('live verification distinguishes an approval denial from an unrelated tool failure', () => {
186 + const batch = {
187 + total_count: 2,
188 + success_count: 1,
189 + error_count: 1,
190 + results: [
191 + { error: null, response: { successful: true, error: null } },
192 + { error: 'User denied tool approval', response: null },
193 + ],
194 + };
195 + expect(() => assertBatch(batch, 1, 1)).not.toThrow();
196 + batch.results[1].error = 'Upstream unavailable';
197 + expect(() => assertBatch(batch, 1, 1)).toThrow();
198 +});
ts/examples/approvals/test/mcp.test.ts new
+64
@@ -0,0 +1,64 @@
1 +import { expect, test } from 'bun:test';
2 +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
3 +import { Server } from '@modelcontextprotocol/sdk/server/index.js';
4 +import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
5 +import { createApprovalClient } from '../src/mcp-client';
6 +import { type ToolRouterInputResponse } from '@composio/core';
7 +
8 +const answers: ToolRouterInputResponse[] = [
9 + { action: 'accept', content: { decision: 'approve' } },
10 + { action: 'accept', content: { decision: 'deny' } },
11 + { action: 'decline' },
12 + { action: 'cancel' },
13 +];
14 +
15 +test.each(answers)('MCP forwards the elicitation answer %j', async answer => {
16 + const server = new Server(
17 + { name: 'approval-test', version: '1.0.0' },
18 + { capabilities: { tools: {} } }
19 + );
20 + server.setRequestHandler(CallToolRequestSchema, async () => {
21 + const response = await server.elicitInput({
22 + mode: 'form',
23 + message: 'Allow the read-only call?',
24 + requestedSchema: {
25 + type: 'object',
26 + properties: { decision: { type: 'string', enum: ['approve', 'deny'] } },
27 + required: ['decision'],
28 + },
29 + });
30 + return { content: [{ type: 'text', text: JSON.stringify(response) }] };
31 + });
32 + let prompts = 0;
33 + const client = createApprovalClient(async question => {
34 + prompts++;
35 + expect(question.message).toBe('Allow the read-only call?');
36 + expect(question.requestedSchema).toHaveProperty('properties.decision');
37 + return answer;
38 + });
39 + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
40 + try {
41 + await server.connect(serverTransport);
42 + await client.connect(clientTransport);
43 + const result = await client.callTool({ name: 'read', arguments: {} });
44 + expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(answer) }]);
45 + expect(prompts).toBe(1);
46 + } finally {
47 + await client.close();
48 + await server.close();
49 + }
50 +});
51 +
52 +test('a client without a handler does not advertise elicitation support', async () => {
53 + const server = new Server({ name: 'approval-test', version: '1.0.0' }, { capabilities: {} });
54 + const client = createApprovalClient();
55 + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
56 + try {
57 + await server.connect(serverTransport);
58 + await client.connect(clientTransport);
59 + expect(server.getClientCapabilities()?.elicitation).toBeUndefined();
60 + } finally {
61 + await client.close();
62 + await server.close();
63 + }
64 +});
ts/examples/approvals/tsconfig.json new
+12
@@ -0,0 +1,12 @@
1 +{
2 + "compilerOptions": {
3 + "target": "es2022",
4 + "module": "esnext",
5 + "moduleResolution": "bundler",
6 + "strict": true,
7 + "esModuleInterop": true,
8 + "skipLibCheck": true,
9 + "types": ["bun"]
10 + },
11 + "include": ["src", "test"]
12 +}