polarion-mcp 1.5.0 → 1.6.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 (105) hide show
  1. package/README.md +12 -21
  2. package/build/code-mode.d.ts +43 -0
  3. package/build/code-mode.js +184 -0
  4. package/build/code-mode.js.map +1 -0
  5. package/build/code-sandbox.d.ts +28 -0
  6. package/build/code-sandbox.js +220 -0
  7. package/build/code-sandbox.js.map +1 -0
  8. package/build/composite-tools.d.ts +1 -1
  9. package/build/composite-tools.js +2 -1
  10. package/build/composite-tools.js.map +1 -1
  11. package/build/composite-trace.js +8 -5
  12. package/build/composite-trace.js.map +1 -1
  13. package/build/composite-upload.js +7 -13
  14. package/build/composite-upload.js.map +1 -1
  15. package/build/composite-workflow.d.ts +3 -0
  16. package/build/composite-workflow.js +93 -0
  17. package/build/composite-workflow.js.map +1 -0
  18. package/build/config.d.ts +7 -22
  19. package/build/config.js +39 -31
  20. package/build/config.js.map +1 -1
  21. package/build/executor.d.ts +2 -1
  22. package/build/executor.js +174 -125
  23. package/build/executor.js.map +1 -1
  24. package/build/guards.d.ts +6 -4
  25. package/build/guards.js +147 -56
  26. package/build/guards.js.map +1 -1
  27. package/build/http-server.js +5 -0
  28. package/build/http-server.js.map +1 -1
  29. package/build/index.js +6 -7
  30. package/build/index.js.map +1 -1
  31. package/build/logger.d.ts +9 -0
  32. package/build/logger.js +10 -0
  33. package/build/logger.js.map +1 -1
  34. package/build/mcp-http-server.d.ts +5 -5
  35. package/build/mcp-http-server.js +28 -54
  36. package/build/mcp-http-server.js.map +1 -1
  37. package/build/profile.d.ts +30 -0
  38. package/build/profile.js +64 -0
  39. package/build/profile.js.map +1 -0
  40. package/build/rest-api.d.ts +3 -0
  41. package/build/rest-api.js +1 -1
  42. package/build/rest-api.js.map +1 -1
  43. package/build/server.d.ts +3 -2
  44. package/build/server.js +41 -110
  45. package/build/server.js.map +1 -1
  46. package/build/tool-execution.d.ts +4 -1
  47. package/build/tool-execution.js +1 -1
  48. package/build/tool-execution.js.map +1 -1
  49. package/build/tool-filter.d.ts +10 -25
  50. package/build/tool-filter.js +15 -34
  51. package/build/tool-filter.js.map +1 -1
  52. package/build/tools.js +530 -300
  53. package/build/tools.js.map +1 -1
  54. package/build/toolsets.d.ts +2 -12
  55. package/build/toolsets.js +1 -26
  56. package/build/toolsets.js.map +1 -1
  57. package/build/utils.d.ts +8 -0
  58. package/build/utils.js +26 -3
  59. package/build/utils.js.map +1 -1
  60. package/build/virtual-tools.d.ts +3 -3
  61. package/build/virtual-tools.js +2 -39
  62. package/build/virtual-tools.js.map +1 -1
  63. package/build/write-verification.d.ts +95 -0
  64. package/build/write-verification.js +280 -0
  65. package/build/write-verification.js.map +1 -0
  66. package/package.json +12 -9
  67. package/src/code-mode.ts +205 -0
  68. package/src/code-sandbox.ts +194 -0
  69. package/src/composite-tools.ts +2 -1
  70. package/src/composite-trace.ts +8 -5
  71. package/src/composite-upload.ts +6 -12
  72. package/src/composite-workflow.ts +74 -0
  73. package/src/config.ts +40 -32
  74. package/src/executor.ts +147 -136
  75. package/src/guards.ts +147 -67
  76. package/src/http-server.ts +5 -0
  77. package/src/index.ts +6 -9
  78. package/src/logger.ts +11 -0
  79. package/src/mcp-http-server.ts +30 -56
  80. package/src/profile.ts +66 -0
  81. package/src/rest-api.ts +4 -1
  82. package/src/server.ts +46 -92
  83. package/src/tool-execution.ts +5 -2
  84. package/src/tool-filter.ts +16 -39
  85. package/src/tools.ts +530 -300
  86. package/src/toolsets.ts +4 -28
  87. package/src/utils.ts +29 -4
  88. package/src/virtual-tools.ts +4 -40
  89. package/src/write-verification.ts +308 -0
  90. package/build/auth.d.ts +0 -38
  91. package/build/auth.js +0 -132
  92. package/build/auth.js.map +0 -1
  93. package/build/generated-from.d.ts +0 -2
  94. package/build/generated-from.js +0 -3
  95. package/build/generated-from.js.map +0 -1
  96. package/build/metadata-cache.d.ts +0 -17
  97. package/build/metadata-cache.js +0 -32
  98. package/build/metadata-cache.js.map +0 -1
  99. package/build/version-check.d.ts +0 -9
  100. package/build/version-check.js +0 -59
  101. package/build/version-check.js.map +0 -1
  102. package/src/auth.ts +0 -141
  103. package/src/generated-from.ts +0 -2
  104. package/src/metadata-cache.ts +0 -30
  105. package/src/version-check.ts +0 -54
package/README.md CHANGED
@@ -5,23 +5,26 @@
5
5
  **Your Polarion work, one conversation away.**
6
6
 
7
7
  Find requirements, review documents and prepare test runs through your AI assistant.
8
- An open-source [Model Context Protocol](https://modelcontextprotocol.io) server that exposes **every Polarion REST operation** (284 tools, generated from the current API definition).
8
+ An open-source [Model Context Protocol](https://modelcontextprotocol.io) server that exposes **every Polarion REST operation** (304 tools, generated from the current API definition).
9
9
 
10
10
  [![CI](https://github.com/phillipboesger/polarion-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/phillipboesger/polarion-mcp/actions/workflows/ci.yml)
11
11
  [![npm version](https://img.shields.io/npm/v/polarion-mcp)](https://www.npmjs.com/package/polarion-mcp)
12
12
  [![Docker image](https://img.shields.io/badge/ghcr.io-polarion--mcp-2496ED?logo=docker&logoColor=white)](https://github.com/phillipboesger/polarion-mcp/pkgs/container/polarion-mcp)
13
13
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
14
14
 
15
- [**Connect your assistant**](https://polarion-mcp.boesger.com/#clients) · [Daily workflows](https://polarion-mcp.boesger.com/#daily-use) · [Tool catalog](src/tools.ts)
15
+ [**Connect your assistant**](https://polarion-mcp.boesger.com/#clients) · [Tool catalog](src/tools.ts)
16
16
 
17
17
  <img src="docs/assets/site-hero.png" alt="Polarion MCP works with Claude, ChatGPT, Gemini, VS Code, Copilot, Cursor and Codex." width="900" />
18
18
 
19
+ <a href="https://polarion-mcp.boesger.com/#demo"><img src="https://raw.githubusercontent.com/phillipboesger/polarion-mcp/main/docs/assets/demo-loop.gif" alt="Claude links new test cases to Polarion requirements, then reads them back to verify." width="900" /></a>
20
+
21
+ <sub>Real claude.ai session, sped up. <a href="https://polarion-mcp.boesger.com/#demo">Watch the 60-second demo</a></sub>
22
+
19
23
  </div>
20
24
 
21
25
  On this page:
22
26
 
23
27
  - [What the connector does for you](#what-the-connector-does-for-you)
24
- - [A day with Polarion MCP](#a-day-with-polarion-mcp)
25
28
  - [Get connected](#get-connected)
26
29
  - [FAQ](#faq)
27
30
  - [Feedback and community](#feedback-and-community)
@@ -36,7 +39,7 @@ On this page:
36
39
 
37
40
  - **Find answers:** search requirements and defects, read LiveDocs and inspect traceability links.
38
41
  - **Prepare work:** draft test cases, prepare runs and record the test outcomes your team supplies.
39
- - **Change data, safely:** the assistant can create and update Polarion data, and every write can be previewed first (`dry_run: true` shows the exact request without sending it). Prefer read access only? `MCP_READ_ONLY=1` blocks all writes. Set approval rules in your AI client; previews do not create an approval lock.
42
+ - **Change data, safely:** preview writes with `dry_run: true`; supported Work Item and LiveDoc writes also verify attributes by reading them back. Prefer read access only? `MCP_READ_ONLY=1` blocks all writes. Set approval rules in your AI client; previews do not create an approval lock.
40
43
  - **Inspect what you run:** MIT source, build provenance and signed container images. See [supply-chain verification](docs/quality/supply-chain.md).
41
44
 
42
45
  ![Topic cards: work items, test management, plans, documents and more, covering every Polarion REST operation](docs/assets/site-coverage.png)
@@ -49,26 +52,12 @@ On this page:
49
52
  | Plans and collections | Review release scope and document collections. |
50
53
  | Projects, people and configuration | Discover accessible projects, users, allowed field values and metadata. |
51
54
 
52
- The [landing page](https://polarion-mcp.boesger.com/#features) shows counts by domain, computed from `src/tools.ts`. The **284 tools** count covers generated REST operations; configured toolsets and additional helpers change the exposed catalog. Selected Work Item writes validate enumeration values, custom-field keys and user references. [Features and limits](docs/features.md) describe the scope.
53
-
54
- ## A day with Polarion MCP
55
-
56
- ![Five example conversations: release triage, document review, test preparation, release status and traceability gaps](docs/assets/site-daily.png)
57
-
58
- These are illustrative conversations using real tools, not recorded outputs. Project types, link roles and permissions vary.
59
-
60
- | Ask your assistant | Tools and result | Your control |
61
- |---|---|---|
62
- | “Which open defects could block this release?” | `getWorkItems`, `getWorkItem`: a scoped list of severity, owners and missing information. | Read-only triage; approve any later reassignment. |
63
- | “Review this LiveDoc and propose clearer acceptance criteria for REQ-17.” | `getDocument`, `getDocumentParts`, `getWorkItem`, `patchWorkItem`: a rewrite of the requirement’s description. | Preview with `dry_run: true`; approve before saving. |
64
- | “Draft tests from these requirements, then record the results I provide.” | `getWorkItems`, `postWorkItems`, `postTestRuns`, `postTestRecords`: proposed cases and a run, then supplied outcomes. | Check existing tests, preview each write and approve. The connector does not execute product tests. |
65
- | “Summarize this release plan and its latest test runs.” | `getPlan`, `getWorkItems`, `getTestRuns`: a draft status update with source IDs and missing data. | You decide release readiness. |
66
- | “Find requirements without a verifies link to a test case.” | `getWorkItems`, `getLinkedWorkItems`: a scoped gap list and existing candidate tests. | Confirm link roles and scope before creating anything. |
67
-
68
- [Explore the chat-style walkthroughs](https://polarion-mcp.boesger.com/#daily-use).
55
+ The [landing page](https://polarion-mcp.boesger.com/#features) shows counts by domain, computed from `src/tools.ts`. The **304 tools** count covers generated REST operations; additional helpers change the exposed catalog. Selected Work Item writes validate enumeration values, custom-field keys and user references. [Features and limits](docs/features.md) describe the scope. To keep the tool list small for large catalogs, see [Code Mode](docs/code-mode.md). Polarion 2612 has a built-in MCP server too: [how the two compare](docs/comparison.md).
69
56
 
70
57
  ## Get connected
71
58
 
59
+ Python users can use the [Python launcher](python/README.md) (`uvx polarion-alm-mcp` or `pip install polarion-alm-mcp`), which starts the matching npm release and requires Node.js 22+ and npm/npx. The PyPI package named `polarion-mcp` belongs to another project.
60
+
72
61
  Two setups, pick by where your client runs. You need a REST-enabled Polarion instance and a PAT. Every guide starts from nothing and ends with a check.
73
62
 
74
63
  | Setup | Use it when | Guide |
@@ -156,6 +145,8 @@ Built by [Phillip Bösger](https://github.com/phillipboesger), building on [@Jon
156
145
 
157
146
  [Docs index](docs/README.md) · [Configuration](docs/configuration.md) · [Deployment](docs/deployment.md) · [Security](docs/security.md) · [Usage](docs/usage.md) · [Architecture](docs/architecture.md) · [Extensions](docs/extensions.md) · [Releases](https://github.com/phillipboesger/polarion-mcp/releases)
158
147
 
148
+ [Publishing and discovery](docs/publishing.md) · [Official MCP Registry](https://registry.modelcontextprotocol.io/?q=io.github.phillipboesger%2Fpolarion-mcp) · [Glama listing](https://glama.ai/mcp/servers/phillipboesger/polarion-mcp)
149
+
159
150
  ## License
160
151
 
161
152
  [MIT](LICENSE) © Phillip Bösger
@@ -0,0 +1,43 @@
1
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
+ import { type SandboxLimits } from './code-sandbox.js';
3
+ import type { VirtualTool } from './virtual-tools.js';
4
+ /** One callable operation in the Code Mode SDK (a generated tool or a composite). */
5
+ export interface SdkOperation {
6
+ name: string;
7
+ description: string;
8
+ inputSchema: Record<string, any>;
9
+ readOnly: boolean;
10
+ /** True when the operation accepts dry_run, so a dry-run execute can preview it. */
11
+ dryRunCapable: boolean;
12
+ toolset?: string;
13
+ }
14
+ export interface CodeModeConfig {
15
+ /** When false, write operations are neither listed nor callable. */
16
+ writes: boolean;
17
+ maxWriteCalls: number;
18
+ limits?: Partial<SandboxLimits>;
19
+ }
20
+ /** Renders a JSON schema as a compact TypeScript type. Unknown shapes degrade to `unknown`. */
21
+ export declare function schemaToType(schema: any, depth?: number): string;
22
+ /** TypeScript declaration the model reads from `search`. */
23
+ export declare function declarationFor(op: SdkOperation): string;
24
+ /** Builds SDK operations from the deployment-filtered tools. Input schemas use the MCP-safe property names the pipeline accepts. */
25
+ export declare function buildSdk(tools: ReadonlyMap<string, {
26
+ name: string;
27
+ description: string;
28
+ inputSchema: any;
29
+ annotations?: {
30
+ readOnlyHint?: boolean;
31
+ };
32
+ }>, composites: readonly VirtualTool[], config: Pick<CodeModeConfig, 'writes'>, toolsetsOf: (name: string) => string, schemaOf: (def: {
33
+ name: string;
34
+ inputSchema: any;
35
+ }) => any): SdkOperation[];
36
+ export declare const CODE_MODE_INSTRUCTIONS: string;
37
+ /** The two tools shown to the client in code mode. `execute` is dispatched by the pipeline (it needs the full call pipeline), so its handler only guards direct misuse. */
38
+ export declare function codeModeTools(ops: readonly SdkOperation[], config: CodeModeConfig): VirtualTool[];
39
+ /**
40
+ * Runs `execute`. Every `polarion.<op>` call goes through `callTool`, which is the full tool pipeline
41
+ * (policy, rate limit, guards, verification, marking, audit), so the sandbox gains no privilege.
42
+ */
43
+ export declare function runExecute(args: Record<string, unknown>, ops: readonly SdkOperation[], config: CodeModeConfig, callTool: (name: string, args: Record<string, unknown>) => Promise<CallToolResult>, signal?: AbortSignal): Promise<CallToolResult>;
@@ -0,0 +1,184 @@
1
+ import { runInSandbox } from './code-sandbox.js';
2
+ import { sanitizeInputSchema } from './utils.js';
3
+ const MAX_DEPTH = 3;
4
+ const MAX_PROPS = 40;
5
+ const IDENT = /^[A-Za-z_$][\w$]*$/;
6
+ /** Renders a JSON schema as a compact TypeScript type. Unknown shapes degrade to `unknown`. */
7
+ export function schemaToType(schema, depth = 0) {
8
+ if (!schema || typeof schema !== 'object')
9
+ return 'unknown';
10
+ if (Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.length <= 12)
11
+ return schema.enum.map((v) => JSON.stringify(v)).join(' | ');
12
+ const variants = schema.oneOf ?? schema.anyOf;
13
+ if (Array.isArray(variants) && variants.length > 0)
14
+ return [...new Set(variants.map((v) => schemaToType(v, depth)))].join(' | ');
15
+ const type = Array.isArray(schema.type) ? schema.type : [schema.type];
16
+ const parts = type.map((t) => {
17
+ switch (t) {
18
+ case 'string': return 'string';
19
+ case 'integer':
20
+ case 'number': return 'number';
21
+ case 'boolean': return 'boolean';
22
+ case 'null': return 'null';
23
+ case 'array': return `${wrap(schemaToType(schema.items, depth + 1))}[]`;
24
+ case 'object':
25
+ case undefined: return objectType(schema, depth);
26
+ default: return 'unknown';
27
+ }
28
+ });
29
+ return [...new Set(parts)].join(' | ');
30
+ }
31
+ const wrap = (type) => /[|{]/.test(type) && !type.startsWith('{') ? `(${type})` : type;
32
+ function objectType(schema, depth) {
33
+ const props = schema.properties && typeof schema.properties === 'object' ? Object.entries(schema.properties) : [];
34
+ if (props.length === 0)
35
+ return schema.additionalProperties && typeof schema.additionalProperties === 'object'
36
+ ? `Record<string, ${schemaToType(schema.additionalProperties, depth + 1)}>` : 'Record<string, unknown>';
37
+ if (depth >= MAX_DEPTH)
38
+ return 'Record<string, unknown>';
39
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
40
+ const shown = props.slice(0, MAX_PROPS).map(([key, value]) => {
41
+ const name = IDENT.test(key) ? key : JSON.stringify(key);
42
+ return `${name}${required.has(key) ? '' : '?'}: ${schemaToType(value, depth + 1)}`;
43
+ });
44
+ if (props.length > MAX_PROPS)
45
+ shown.push('[key: string]: unknown');
46
+ return `{ ${shown.join('; ')} }`;
47
+ }
48
+ /** TypeScript declaration the model reads from `search`. */
49
+ export function declarationFor(op) {
50
+ const args = schemaToType(op.inputSchema);
51
+ const doc = op.description.split(/[\r\n]/)[0].slice(0, 200);
52
+ const flags = op.readOnly ? '' : ' [write]';
53
+ return `/** ${doc}${flags} */\npolarion.${op.name}(args: ${args === 'Record<string, unknown>' ? '{}' : args}): Promise<any>;`;
54
+ }
55
+ /** Builds SDK operations from the deployment-filtered tools. Input schemas use the MCP-safe property names the pipeline accepts. */
56
+ export function buildSdk(tools, composites, config, toolsetsOf, schemaOf) {
57
+ const ops = [];
58
+ for (const def of tools.values()) {
59
+ const schema = schemaOf(def);
60
+ const readOnly = def.annotations?.readOnlyHint === true;
61
+ ops.push({ name: def.name, description: def.description, inputSchema: schema, readOnly, dryRunCapable: schema?.properties?.dry_run !== undefined, toolset: toolsetsOf(def.name) });
62
+ }
63
+ for (const tool of composites) {
64
+ ops.push({
65
+ name: tool.name, description: tool.description, inputSchema: sanitizeInputSchema(tool.inputSchema),
66
+ readOnly: tool.annotations?.readOnlyHint === true, dryRunCapable: tool.dryRunSafe === true, toolset: 'composites',
67
+ });
68
+ }
69
+ return ops.filter(op => config.writes || op.readOnly);
70
+ }
71
+ function rank(ops, query, toolset, limit) {
72
+ const terms = [...query.toLowerCase().matchAll(/[a-z0-9]+/g)].map(m => m[0]);
73
+ const scored = ops.map(op => {
74
+ const name = op.name.toLowerCase();
75
+ const haystack = `${name} ${op.description} ${op.toolset ?? ''}`.toLowerCase();
76
+ const score = terms.reduce((sum, term) => sum + (name === term ? 5 : name.includes(term) ? 3 : haystack.includes(term) ? 1 : 0), 0);
77
+ // Composites are the friendliest entry points, so they win ties.
78
+ return { op, score: score + (op.toolset === 'composites' && score > 0 ? 1 : 0) };
79
+ }).filter(row => (terms.length === 0 || row.score > 0) && (!toolset || row.op.toolset === toolset));
80
+ return scored.sort((a, b) => b.score - a.score || a.op.name.localeCompare(b.op.name)).slice(0, limit).map(row => row.op);
81
+ }
82
+ export const CODE_MODE_INSTRUCTIONS = [
83
+ 'Code Mode: this server exposes two tools. `search` finds Polarion operations and returns TypeScript declarations; `execute` runs JavaScript that calls them.',
84
+ 'Inside `execute`, call `await polarion.<operation>({...})` (the declarations from `search`), use plain JavaScript to loop, filter and join, `return` a small JSON value, and use console.log sparingly.',
85
+ 'Search first, then write one script that does the whole task. Writes honour dry_run, read-only mode, validation and read-back verification exactly as direct tool calls do; run with dry_run: true first.',
86
+ ].join(' ');
87
+ /** The two tools shown to the client in code mode. `execute` is dispatched by the pipeline (it needs the full call pipeline), so its handler only guards direct misuse. */
88
+ export function codeModeTools(ops, config) {
89
+ const writeNote = config.writes ? '' : ' This deployment is read-only for Code Mode: write operations are not available.';
90
+ const search = {
91
+ name: 'search', title: 'Search Polarion operations', toolset: 'composites',
92
+ description: `Find Polarion operations by keyword and get their TypeScript declarations for use inside \`execute\`. Returns at most ${'`limit`'} matches (default 8).`,
93
+ inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'Keywords, e.g. "trace links" or "create work item".' }, toolset: { type: 'string', description: 'Optional toolset filter, e.g. composites.' }, limit: { type: 'number', default: 8 } } },
94
+ annotations: { readOnlyHint: true },
95
+ handler: ({ query = '', toolset, limit = 8 }) => {
96
+ const matches = rank(ops, String(query), typeof toolset === 'string' ? toolset : undefined, Math.max(1, Math.min(25, Number(limit) || 8)));
97
+ if (matches.length === 0)
98
+ return { content: [{ type: 'text', text: `No operations match "${String(query)}". ${ops.length} operations are available; try broader keywords.` }] };
99
+ return { content: [{ type: 'text', text: matches.map(declarationFor).join('\n\n') }] };
100
+ },
101
+ };
102
+ const execute = {
103
+ name: 'execute', title: 'Run Polarion script', toolset: 'composites', dryRunSafe: true,
104
+ description: `Run JavaScript in an isolated sandbox. The only API is \`polarion.<operation>(args)\` (see \`search\`) and console.log. The code is the body of an async function: use await, return a JSON value. Limits: ${Math.round((config.limits?.timeoutMs ?? 30_000) / 1000)} s, ${config.maxWriteCalls} write calls. With dry_run: true every write is previewed, not performed.${writeNote}`,
105
+ inputSchema: { type: 'object', properties: { code: { type: 'string', description: 'Body of an async function, e.g. const r = await polarion.getProjects({}); return r.data.length;' }, dry_run: { type: 'boolean', description: 'Preview all writes without performing them.' } }, required: ['code'] },
106
+ annotations: { readOnlyHint: !config.writes, destructiveHint: config.writes, openWorldHint: true },
107
+ handler: (args, ctx) => ctx.callTool
108
+ ? runExecute(args, ops, config, (name, callArgs) => ctx.callTool(name, callArgs), ctx.signal)
109
+ : { content: [{ type: 'text', text: 'Error: execute needs the server pipeline' }], isError: true },
110
+ };
111
+ return [search, execute];
112
+ }
113
+ function unwrap(result) {
114
+ if (result.structuredContent !== undefined)
115
+ return result.structuredContent;
116
+ const text = result.content.filter(item => item.type === 'text').map(item => item.text).join('\n');
117
+ try {
118
+ return JSON.parse(text);
119
+ }
120
+ catch {
121
+ return text;
122
+ }
123
+ }
124
+ /**
125
+ * Runs `execute`. Every `polarion.<op>` call goes through `callTool`, which is the full tool pipeline
126
+ * (policy, rate limit, guards, verification, marking, audit), so the sandbox gains no privilege.
127
+ */
128
+ export async function runExecute(args, ops, config, callTool, signal) {
129
+ const code = typeof args.code === 'string' ? args.code : '';
130
+ if (!code.trim())
131
+ return { content: [{ type: 'text', text: 'Error: code is required' }], isError: true };
132
+ const dryRun = args.dry_run === true;
133
+ let writeCalls = 0;
134
+ const inFlight = new Set();
135
+ const host = {};
136
+ for (const op of ops) {
137
+ host[op.name] = (callArgs) => {
138
+ const running = hostCall(op, callArgs);
139
+ inFlight.add(running);
140
+ void running.finally(() => inFlight.delete(running)).catch(() => undefined);
141
+ return running;
142
+ };
143
+ const hostCall = async (op, callArgs) => {
144
+ const input = { ...callArgs };
145
+ // Confirmation is the human's decision (elicitation); code can not grant it.
146
+ delete input.confirm;
147
+ if (!op.readOnly) {
148
+ if (!config.writes)
149
+ throw new Error(`${op.name} is a write operation and Code Mode writes are disabled`);
150
+ if (dryRun && !op.dryRunCapable)
151
+ throw new Error(`${op.name} does not support dry_run, so it is blocked in a dry-run execute`);
152
+ writeCalls += 1;
153
+ if (writeCalls > config.maxWriteCalls)
154
+ throw new Error(`Write call limit of ${config.maxWriteCalls} exceeded`);
155
+ if (dryRun)
156
+ input.dry_run = true;
157
+ }
158
+ const result = await callTool(op.name, input);
159
+ if (result.isError) {
160
+ const text = result.content.filter(item => item.type === 'text').map(item => item.text).join(' ');
161
+ throw new Error(text || `${op.name} failed`);
162
+ }
163
+ return unwrap(result);
164
+ };
165
+ }
166
+ const outcome = await runInSandbox(code, host, { limits: config.limits, signal });
167
+ // Calls the script started but did not await keep running in the pipeline; wait for them so the counts and the result are final.
168
+ if (inFlight.size > 0) {
169
+ let timer;
170
+ await Promise.race([Promise.allSettled([...inFlight]), new Promise(resolve => { timer = setTimeout(resolve, 15_000); })]);
171
+ clearTimeout(timer);
172
+ }
173
+ const payload = {
174
+ ...(outcome.ok ? { result: outcome.value === undefined ? null : outcome.value } : { error: outcome.error?.message ?? 'Execution failed' }),
175
+ ...(outcome.logs ? { logs: outcome.logs } : {}),
176
+ host_calls: outcome.hostCalls,
177
+ ...(inFlight.size > 0 ? { pending_calls: inFlight.size } : {}),
178
+ write_calls: writeCalls,
179
+ ...(dryRun ? { dry_run: true } : {}),
180
+ ...(outcome.truncated ? { truncated: true } : {}),
181
+ };
182
+ return { content: [{ type: 'text', text: JSON.stringify(payload) }], ...(outcome.ok ? {} : { isError: true }) };
183
+ }
184
+ //# sourceMappingURL=code-mode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-mode.js","sourceRoot":"","sources":["../src/code-mode.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAyC,MAAM,mBAAmB,CAAC;AACxF,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAqBjD,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,MAAM,KAAK,GAAG,oBAAoB,CAAC;AAEnC,+FAA+F;AAC/F,MAAM,UAAU,YAAY,CAAC,MAAW,EAAE,KAAK,GAAG,CAAC;IACjD,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAC5D,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE;QAAE,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAU,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5J,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,CAAC;IAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,YAAY,CAAC,CAAC,EAAE,KAAK,CA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CAAC,CAAC,EAAE,aAAa,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9D,WAAW,EAAE,UAAU;QACvB,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACpC,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAClD,CAAC;IACF,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AAClH,CAAC"}
@@ -0,0 +1,28 @@
1
+ export interface SandboxLimits {
2
+ timeoutMs: number;
3
+ memoryBytes: number;
4
+ maxStackBytes: number;
5
+ maxHostCalls: number;
6
+ maxLogBytes: number;
7
+ maxResultBytes: number;
8
+ }
9
+ export declare const DEFAULT_SANDBOX_LIMITS: SandboxLimits;
10
+ export type HostFunction = (args: unknown) => Promise<unknown>;
11
+ export interface SandboxResult {
12
+ ok: boolean;
13
+ value?: unknown;
14
+ error?: {
15
+ message: string;
16
+ };
17
+ logs: string;
18
+ hostCalls: number;
19
+ truncated: boolean;
20
+ }
21
+ /**
22
+ * Runs `code` (the body of an async function) in a fresh QuickJS WASM context.
23
+ * The sandbox sees only `polarion.<name>(args)` and `console`; no fs, network, process, timers or modules.
24
+ */
25
+ export declare function runInSandbox(code: string, hostFunctions: Record<string, HostFunction>, opts?: {
26
+ limits?: Partial<SandboxLimits>;
27
+ signal?: AbortSignal;
28
+ }): Promise<SandboxResult>;
@@ -0,0 +1,220 @@
1
+ import { newQuickJSWASMModule, shouldInterruptAfterDeadline } from 'quickjs-emscripten';
2
+ export const DEFAULT_SANDBOX_LIMITS = {
3
+ timeoutMs: 30_000,
4
+ memoryBytes: 64 * 1024 * 1024,
5
+ maxStackBytes: 512 * 1024,
6
+ maxHostCalls: 100,
7
+ maxLogBytes: 8 * 1024,
8
+ maxResultBytes: 256 * 1024,
9
+ };
10
+ let modulePromise;
11
+ const loadModule = () => (modulePromise ??= newQuickJSWASMModule());
12
+ /** Never let host paths or stack frames cross into a result: keep the first line only and cap its length. */
13
+ function cleanMessage(value) {
14
+ const raw = typeof value === 'string' ? value : value instanceof Error ? value.message : 'Unknown error';
15
+ const line = raw.split('\n').find(part => part.trim() && !/^\s*at\s/.test(part)) ?? 'Unknown error';
16
+ return line.replace(/(?:[A-Za-z]:)?(?:\/[\w.@-]+){2,}/g, '<path>').slice(0, 500);
17
+ }
18
+ function dumpError(vm, handle) {
19
+ // Read the message property directly: vm.dump() calls the sandbox's JSON.stringify, which untrusted code can replace.
20
+ if (vm.typeof(handle) === 'string')
21
+ return cleanMessage(vm.getString(handle));
22
+ if (vm.typeof(handle) !== 'object')
23
+ return 'Sandbox error';
24
+ const message = vm.getProp(handle, 'message');
25
+ try {
26
+ return vm.typeof(message) === 'string' ? cleanMessage(vm.getString(message)) : 'Sandbox error';
27
+ }
28
+ finally {
29
+ message.dispose();
30
+ }
31
+ }
32
+ // Runs before untrusted code. `__host`/`__log` are the only bridge; both are removed from the global afterwards.
33
+ // Arguments and results cross as JSON strings, so host code only ever sees plain data parsed on the host side.
34
+ const bootstrap = (names) => `
35
+ (() => {
36
+ const host = globalThis.__host; const log = globalThis.__log;
37
+ delete globalThis.__host; delete globalThis.__log;
38
+ const stringify = JSON.stringify; const parse = JSON.parse;
39
+ const api = {};
40
+ for (const name of ${JSON.stringify(names)}) {
41
+ api[name] = async (args) => {
42
+ const text = stringify(args === undefined ? {} : args);
43
+ const reply = await host(name, text === undefined ? '{}' : text);
44
+ return reply === '' ? undefined : parse(reply);
45
+ };
46
+ }
47
+ Object.defineProperty(globalThis, '__ser', { value: (v) => stringify(v), writable: false, configurable: false });
48
+ Object.defineProperty(globalThis, 'polarion', { value: Object.freeze(api), writable: false, configurable: false });
49
+ const fmt = (value) => { if (typeof value === 'string') return value; try { const text = stringify(value); return text === undefined ? String(value) : text; } catch { return String(value); } };
50
+ const write = (...parts) => log(parts.map(fmt).join(' '));
51
+ Object.defineProperty(globalThis, 'console', { value: Object.freeze({ log: write, info: write, warn: write, error: write }), writable: false, configurable: false });
52
+ })();
53
+ `;
54
+ /**
55
+ * Runs `code` (the body of an async function) in a fresh QuickJS WASM context.
56
+ * The sandbox sees only `polarion.<name>(args)` and `console`; no fs, network, process, timers or modules.
57
+ */
58
+ export async function runInSandbox(code, hostFunctions, opts = {}) {
59
+ const limits = { ...DEFAULT_SANDBOX_LIMITS, ...opts.limits };
60
+ const quickjs = await loadModule();
61
+ const runtime = quickjs.newRuntime();
62
+ const vm = runtime.newContext();
63
+ const deadline = Date.now() + limits.timeoutMs;
64
+ let logs = '';
65
+ let logTruncated = false;
66
+ let hostCalls = 0;
67
+ const pending = new Set();
68
+ const result = { ok: false, logs: '', hostCalls: 0, truncated: false };
69
+ try {
70
+ runtime.setMemoryLimit(limits.memoryBytes);
71
+ runtime.setMaxStackSize(limits.maxStackBytes);
72
+ runtime.setInterruptHandler(shouldInterruptAfterDeadline(deadline));
73
+ const logFn = vm.newFunction('__log', textHandle => {
74
+ const text = String(vm.getString(textHandle));
75
+ if (logTruncated)
76
+ return;
77
+ const next = logs ? `${logs}\n${text}` : text;
78
+ if (next.length > limits.maxLogBytes) {
79
+ logs = next.slice(0, limits.maxLogBytes);
80
+ logTruncated = true;
81
+ }
82
+ else
83
+ logs = next;
84
+ });
85
+ vm.setProp(vm.global, '__log', logFn);
86
+ logFn.dispose();
87
+ const hostFn = vm.newFunction('__host', (nameHandle, argsHandle) => {
88
+ const name = vm.getString(nameHandle);
89
+ const argsText = vm.getString(argsHandle);
90
+ const deferred = vm.newPromise();
91
+ pending.add(deferred);
92
+ const reject = (message) => {
93
+ if (!deferred.alive)
94
+ return;
95
+ const error = vm.newError(message);
96
+ deferred.reject(error);
97
+ error.dispose();
98
+ };
99
+ hostCalls += 1;
100
+ const fn = Object.hasOwn(hostFunctions, name) ? hostFunctions[name] : undefined;
101
+ if (hostCalls > limits.maxHostCalls)
102
+ reject(`Host call limit of ${limits.maxHostCalls} exceeded`);
103
+ else if (!fn)
104
+ reject(`Unknown function: ${name}`);
105
+ else {
106
+ let parsed;
107
+ try {
108
+ parsed = JSON.parse(argsText);
109
+ }
110
+ catch {
111
+ reject('Arguments must be JSON-serializable');
112
+ }
113
+ if (parsed !== undefined && (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))) {
114
+ reject('Arguments must be an object');
115
+ parsed = undefined;
116
+ }
117
+ if (parsed !== undefined) {
118
+ Promise.resolve().then(() => fn(parsed)).then(value => {
119
+ if (!deferred.alive)
120
+ return;
121
+ const text = value === undefined ? '' : JSON.stringify(value);
122
+ if ((text?.length ?? 0) > limits.maxResultBytes) {
123
+ reject(`Host result too large (${text.length} characters, limit ${limits.maxResultBytes}); request fewer fields or a smaller page`);
124
+ return;
125
+ }
126
+ const handle = vm.newString(text ?? '');
127
+ deferred.resolve(handle);
128
+ handle.dispose();
129
+ }, (error) => reject(cleanMessage(error)));
130
+ }
131
+ }
132
+ return deferred.handle;
133
+ });
134
+ vm.setProp(vm.global, '__host', hostFn);
135
+ hostFn.dispose();
136
+ const boot = vm.evalCode(bootstrap(Object.keys(hostFunctions)));
137
+ if (boot.error) {
138
+ result.error = { message: dumpError(vm, boot.error) };
139
+ boot.error.dispose();
140
+ return result;
141
+ }
142
+ boot.value.dispose();
143
+ // The wrapper serializes inside the sandbox, so only a JSON string ever leaves it.
144
+ const wrapped = `(async () => {
145
+ const __value = await (async () => {\n${code}\n})();
146
+ if (typeof __value === 'function' || typeof __value === 'symbol') throw new Error('Result is not JSON-serializable');
147
+ return __value === undefined ? '' : __ser(__value);
148
+ })()`;
149
+ const started = vm.evalCode(wrapped, 'sandbox.js');
150
+ if (started.error) {
151
+ result.error = { message: dumpError(vm, started.error) };
152
+ started.error.dispose();
153
+ return result;
154
+ }
155
+ let settled;
156
+ const promiseHandle = started.value;
157
+ void vm.resolvePromise(promiseHandle).then(outcome => {
158
+ if (outcome.error) {
159
+ settled = { error: dumpError(vm, outcome.error) };
160
+ outcome.error.dispose();
161
+ }
162
+ else {
163
+ // User code can return from the wrapper early; only a string is a valid serialized result.
164
+ settled = vm.typeof(outcome.value) === 'string' ? { text: vm.getString(outcome.value) } : { error: 'Result is not JSON-serializable' };
165
+ outcome.value.dispose();
166
+ }
167
+ });
168
+ promiseHandle.dispose();
169
+ const abortError = () => opts.signal?.aborted ? 'Execution aborted' : Date.now() > deadline ? 'Execution timed out' : undefined;
170
+ while (!settled) {
171
+ const stop = abortError();
172
+ if (stop) {
173
+ settled = { error: stop };
174
+ break;
175
+ }
176
+ const jobs = runtime.executePendingJobs();
177
+ if (jobs.error) {
178
+ settled = { error: dumpError(vm, jobs.error) };
179
+ jobs.error.dispose();
180
+ break;
181
+ }
182
+ if (!settled)
183
+ await new Promise(resolve => setImmediate(resolve));
184
+ }
185
+ if (settled.error === undefined && Date.now() > deadline)
186
+ settled = { error: 'Execution timed out' };
187
+ if (settled.error !== undefined) {
188
+ result.error = { message: /interrupted/i.test(settled.error) ? 'Execution timed out' : settled.error };
189
+ }
190
+ else {
191
+ const text = settled.text ?? '';
192
+ if (text.length > limits.maxResultBytes) {
193
+ result.truncated = true;
194
+ result.value = `${text.slice(0, limits.maxResultBytes)}`;
195
+ }
196
+ else {
197
+ result.value = text === '' ? undefined : JSON.parse(text);
198
+ }
199
+ result.ok = true;
200
+ }
201
+ return result;
202
+ }
203
+ catch (error) {
204
+ result.error = { message: cleanMessage(error) };
205
+ return result;
206
+ }
207
+ finally {
208
+ result.logs = logTruncated ? `${logs}\n[logs truncated]` : logs;
209
+ result.hostCalls = hostCalls;
210
+ for (const deferred of pending)
211
+ if (deferred.alive)
212
+ deferred.dispose();
213
+ try {
214
+ vm.dispose();
215
+ runtime.dispose();
216
+ }
217
+ catch { /* A leaked handle after an interrupt must not mask the result. */ }
218
+ }
219
+ }
220
+ //# sourceMappingURL=code-sandbox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-sandbox.js","sourceRoot":"","sources":["../src/code-sandbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,4BAA4B,EAAmE,MAAM,oBAAoB,CAAC;AAUzJ,MAAM,CAAC,MAAM,sBAAsB,GAAkB;IACnD,SAAS,EAAE,MAAM;IACjB,WAAW,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;IAC7B,aAAa,EAAE,GAAG,GAAG,IAAI;IACzB,YAAY,EAAE,GAAG;IACjB,WAAW,EAAE,CAAC,GAAG,IAAI;IACrB,cAAc,EAAE,GAAG,GAAG,IAAI;CAC3B,CAAC;AAWF,IAAI,aAAqD,CAAC;AAC1D,MAAM,UAAU,GAAG,GAA+B,EAAE,CAAC,CAAC,aAAa,KAAK,oBAAoB,EAAE,CAAC,CAAC;AAEhG,6GAA6G;AAC7G,SAAS,YAAY,CAAC,KAAc;IAClC,MAAM,GAAG,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,CAAC;IACzG,MAAM,IAAI,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,eAAe,CAAC;IACpG,OAAO,IAAI,CAAC,OAAO,CAAC,mCAAmC,EAAE,QAAQ,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,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,CAAC;QAAC,CAAC;QAAC,MAAM,CAAC,CAAC,kEAAkE,CAAC,CAAC;IACvH,CAAC;AACH,CAAC"}
@@ -1 +1 @@
1
- export declare const COMPOSITE_TOOLS: readonly [import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool];
1
+ export declare const COMPOSITE_TOOLS: readonly [import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool, import("./virtual-tools.js").VirtualTool];
@@ -1,7 +1,8 @@
1
+ import { getWorkitemActions, transitionWorkitemStatus } from './composite-workflow.js';
1
2
  import { runJobAndWait } from './composite-jobs.js';
2
3
  import { traceLinks } from './composite-trace.js';
3
4
  import { getOutline, readDocument, readSection } from './composite-documents.js';
4
5
  import { compositeTools as searchTools } from './composite-search.js';
5
6
  import { uploadAttachment } from './composite-upload.js';
6
- export const COMPOSITE_TOOLS = [runJobAndWait, traceLinks, readDocument, getOutline, readSection, uploadAttachment, ...searchTools];
7
+ export const COMPOSITE_TOOLS = [getWorkitemActions, transitionWorkitemStatus, runJobAndWait, traceLinks, readDocument, getOutline, readSection, uploadAttachment, ...searchTools];
7
8
  //# sourceMappingURL=composite-tools.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"composite-tools.js","sourceRoot":"","sources":["../src/composite-tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACjF,OAAO,EAAE,cAAc,IAAI,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,gBAAgB,EAAE,GAAG,WAAW,CAAU,CAAC"}
1
+ {"version":3,"file":"composite-tools.js","sourceRoot":"","sources":["../src/composite-tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AACvF,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACjF,OAAO,EAAE,cAAc,IAAI,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,kBAAkB,EAAE,wBAAwB,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,gBAAgB,EAAE,GAAG,WAAW,CAAU,CAAC"}