@agllama/mcp 0.7.1 → 0.7.3

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 (118) hide show
  1. package/README.md +68 -18
  2. package/dist/__tests__/api-client.dispatch.test.d.ts +2 -0
  3. package/dist/__tests__/api-client.dispatch.test.d.ts.map +1 -0
  4. package/dist/__tests__/api-client.dispatch.test.js +243 -0
  5. package/dist/__tests__/api-client.dispatch.test.js.map +1 -0
  6. package/dist/api-client.d.ts +104 -4
  7. package/dist/api-client.d.ts.map +1 -1
  8. package/dist/api-client.js +165 -49
  9. package/dist/api-client.js.map +1 -1
  10. package/dist/hosted/__tests__/context.test.d.ts +2 -0
  11. package/dist/hosted/__tests__/context.test.d.ts.map +1 -0
  12. package/dist/hosted/__tests__/context.test.js +77 -0
  13. package/dist/hosted/__tests__/context.test.js.map +1 -0
  14. package/dist/hosted/__tests__/toolSurface.test.d.ts +2 -0
  15. package/dist/hosted/__tests__/toolSurface.test.d.ts.map +1 -0
  16. package/dist/hosted/__tests__/toolSurface.test.js +20 -0
  17. package/dist/hosted/__tests__/toolSurface.test.js.map +1 -0
  18. package/dist/hosted/context.d.ts +11 -0
  19. package/dist/hosted/context.d.ts.map +1 -0
  20. package/dist/hosted/context.js +39 -0
  21. package/dist/hosted/context.js.map +1 -0
  22. package/dist/hosted/toolSurface.d.ts +21 -0
  23. package/dist/hosted/toolSurface.d.ts.map +1 -0
  24. package/dist/hosted/toolSurface.js +51 -0
  25. package/dist/hosted/toolSurface.js.map +1 -0
  26. package/dist/index.js +0 -0
  27. package/dist/server.d.ts +8 -0
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +76 -2
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/__tests__/connect.test.d.ts +2 -0
  32. package/dist/tools/__tests__/connect.test.d.ts.map +1 -0
  33. package/dist/tools/__tests__/connect.test.js +57 -0
  34. package/dist/tools/__tests__/connect.test.js.map +1 -0
  35. package/dist/tools/__tests__/prScorer.test.js +7 -0
  36. package/dist/tools/__tests__/prScorer.test.js.map +1 -1
  37. package/dist/tools/__tests__/session.test.js +165 -1
  38. package/dist/tools/__tests__/session.test.js.map +1 -1
  39. package/dist/tools/__tests__/skills.createSkill.hosted.test.d.ts +2 -0
  40. package/dist/tools/__tests__/skills.createSkill.hosted.test.d.ts.map +1 -0
  41. package/dist/tools/__tests__/skills.createSkill.hosted.test.js +102 -0
  42. package/dist/tools/__tests__/skills.createSkill.hosted.test.js.map +1 -0
  43. package/dist/tools/analytics.js +3 -3
  44. package/dist/tools/analytics.js.map +1 -1
  45. package/dist/tools/attachments.js +3 -3
  46. package/dist/tools/attachments.js.map +1 -1
  47. package/dist/tools/backlog.js +4 -4
  48. package/dist/tools/backlog.js.map +1 -1
  49. package/dist/tools/boardConfig.js +2 -2
  50. package/dist/tools/boardConfig.js.map +1 -1
  51. package/dist/tools/boards.js +4 -4
  52. package/dist/tools/boards.js.map +1 -1
  53. package/dist/tools/codeDocs.d.ts +166 -0
  54. package/dist/tools/codeDocs.d.ts.map +1 -0
  55. package/dist/tools/codeDocs.js +332 -0
  56. package/dist/tools/codeDocs.js.map +1 -0
  57. package/dist/tools/comments.js +2 -2
  58. package/dist/tools/comments.js.map +1 -1
  59. package/dist/tools/connect.d.ts.map +1 -1
  60. package/dist/tools/connect.js +26 -13
  61. package/dist/tools/connect.js.map +1 -1
  62. package/dist/tools/context.js +2 -2
  63. package/dist/tools/context.js.map +1 -1
  64. package/dist/tools/devLinks.js +2 -2
  65. package/dist/tools/devLinks.js.map +1 -1
  66. package/dist/tools/epicSignOff.js +2 -2
  67. package/dist/tools/epicSignOff.js.map +1 -1
  68. package/dist/tools/help.d.ts.map +1 -1
  69. package/dist/tools/help.js +25 -2
  70. package/dist/tools/help.js.map +1 -1
  71. package/dist/tools/index.d.ts +1 -0
  72. package/dist/tools/index.d.ts.map +1 -1
  73. package/dist/tools/index.js +1 -0
  74. package/dist/tools/index.js.map +1 -1
  75. package/dist/tools/issueLinks.js +3 -3
  76. package/dist/tools/issueLinks.js.map +1 -1
  77. package/dist/tools/issuePlanLinks.js +2 -2
  78. package/dist/tools/issuePlanLinks.js.map +1 -1
  79. package/dist/tools/issues.js +7 -7
  80. package/dist/tools/issues.js.map +1 -1
  81. package/dist/tools/labels.js +3 -3
  82. package/dist/tools/labels.js.map +1 -1
  83. package/dist/tools/notificationRules.js +2 -2
  84. package/dist/tools/notificationRules.js.map +1 -1
  85. package/dist/tools/plans.d.ts +18 -3
  86. package/dist/tools/plans.d.ts.map +1 -1
  87. package/dist/tools/plans.js +45 -8
  88. package/dist/tools/plans.js.map +1 -1
  89. package/dist/tools/prScorer.js +3 -3
  90. package/dist/tools/prScorer.js.map +1 -1
  91. package/dist/tools/prScorerHistory.js +2 -2
  92. package/dist/tools/prScorerHistory.js.map +1 -1
  93. package/dist/tools/projectErrors.d.ts +2 -2
  94. package/dist/tools/projectErrors.js +2 -2
  95. package/dist/tools/projectErrors.js.map +1 -1
  96. package/dist/tools/prompts.js +7 -7
  97. package/dist/tools/prompts.js.map +1 -1
  98. package/dist/tools/refinement.js +3 -3
  99. package/dist/tools/refinement.js.map +1 -1
  100. package/dist/tools/roadmap.js +2 -2
  101. package/dist/tools/roadmap.js.map +1 -1
  102. package/dist/tools/rollup.js +2 -2
  103. package/dist/tools/rollup.js.map +1 -1
  104. package/dist/tools/search.d.ts +2 -2
  105. package/dist/tools/search.js +2 -2
  106. package/dist/tools/search.js.map +1 -1
  107. package/dist/tools/session.d.ts +33 -2
  108. package/dist/tools/session.d.ts.map +1 -1
  109. package/dist/tools/session.js +104 -7
  110. package/dist/tools/session.js.map +1 -1
  111. package/dist/tools/skills.d.ts.map +1 -1
  112. package/dist/tools/skills.js +21 -0
  113. package/dist/tools/skills.js.map +1 -1
  114. package/dist/tools/sprints.js +4 -4
  115. package/dist/tools/sprints.js.map +1 -1
  116. package/dist/types.d.ts +84 -0
  117. package/dist/types.d.ts.map +1 -1
  118. package/package.json +21 -4
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
5
5
  [![Node.js Version](https://img.shields.io/node/v/@agllama/mcp.svg)](https://nodejs.org)
6
6
 
7
- Connect Claude AI to [AG-Llama](https://agllama.onrender.com) project management using the Model Context Protocol (MCP). Manage issues, sprints, and boards directly from your AI assistant.
7
+ Connect your AI client to [AG-Llama](https://agllama.onrender.com) project management using the Model Context Protocol (MCP). Manage issues, sprints, and boards directly from Claude Code, Claude Desktop, Codex CLI, Cursor, Gemini CLI, or VS Code/Copilot.
8
8
 
9
9
  > **Not affiliated with LlamaIndex, LlamaCloud, or Meta's Llama models.** "AG-Llama" is an independent agile project-management tool. Published and maintained by Keith Willis (`admin@ag-llama.com`); source at [github.com/WillisK-0/J-Killer](https://github.com/WillisK-0/J-Killer) under `packages/mcp-server`.
10
10
  >
@@ -12,7 +12,7 @@ Connect Claude AI to [AG-Llama](https://agllama.onrender.com) project management
12
12
 
13
13
  ## What is AG-Llama?
14
14
 
15
- AG-Llama is a modern, lightweight Jira alternative for agile teams. This MCP server lets Claude AI interact with your projects, create issues, manage sprints, and automate workflows without leaving your conversation.
15
+ AG-Llama is a modern, lightweight Jira alternative for agile teams. This MCP server lets your AI client interact with your projects, create issues, manage sprints, and automate workflows without leaving your conversation.
16
16
 
17
17
  ## Installation
18
18
 
@@ -27,14 +27,16 @@ npx @agllama/mcp
27
27
  ### 1. Get Your API Key
28
28
 
29
29
  1. Sign up at **[agllama.onrender.com](https://agllama.onrender.com)**
30
- 2. Navigate to **Settings > API Keys**
31
- 3. Click **"Generate API Key"**
30
+ 2. Navigate to **Profile → MCP Integration**
31
+ 3. Click **"Generate API key"**
32
32
  4. Copy the key (shown only once)
33
33
 
34
34
  ### 2. Configure your MCP client
35
35
 
36
- AG-Llama is MCP-native — pick your client below. The Claude config stays byte-identical to past
37
- versions; Codex / Cursor / Generic sections are additive.
36
+ AG-Llama is MCP-native — pick your client below. Six clients work today: **Claude Code, Claude
37
+ Desktop, Codex CLI, Cursor, Gemini CLI, and VS Code/Copilot.** Every client but VS Code uses an
38
+ `mcpServers` JSON block; VS Code uses `servers` (no `mcpServers` fallback); Codex CLI uses TOML.
39
+ The Claude config stays byte-identical to past versions; the other sections are additive.
38
40
 
39
41
  > Config formats verified 2026-05-24:
40
42
  > - Cursor: https://cursor.com/docs/context/mcp
@@ -138,6 +140,48 @@ Edit `~/.cursor/mcp.json` (user-wide) or `.cursor/mcp.json` (project):
138
140
  }
139
141
  ```
140
142
 
143
+ #### For Gemini CLI
144
+
145
+ Edit `~/.gemini/settings.json`:
146
+
147
+ ```json
148
+ {
149
+ "mcpServers": {
150
+ "llama": {
151
+ "command": "npx",
152
+ "args": ["-y", "@agllama/mcp"],
153
+ "env": {
154
+ "LLAMA_API_URL": "https://api.ag-llama.com",
155
+ "LLAMA_API_KEY": "llm_xxxxxxxx"
156
+ }
157
+ }
158
+ }
159
+ }
160
+ ```
161
+
162
+ #### For VS Code / GitHub Copilot
163
+
164
+ Edit `.vscode/mcp.json` in your project (or run the Command Palette action **MCP: Open User
165
+ Configuration** for a user-wide config). VS Code's top-level key is **`servers`**, not
166
+ `mcpServers` — there is no `mcpServers` fallback, so pasting a Claude-style config here fails
167
+ silently. Requires **VS Code 1.102 or later**, the release where MCP support went GA and the
168
+ `servers` key became supported.
169
+
170
+ ```json
171
+ {
172
+ "servers": {
173
+ "llama": {
174
+ "command": "npx",
175
+ "args": ["-y", "@agllama/mcp"],
176
+ "env": {
177
+ "LLAMA_API_URL": "https://api.ag-llama.com",
178
+ "LLAMA_API_KEY": "llm_xxxxxxxx"
179
+ }
180
+ }
181
+ }
182
+ }
183
+ ```
184
+
141
185
  #### For any other MCP client (Generic)
142
186
 
143
187
  Any MCP client that supports stdio transport can connect with the raw command and env vars:
@@ -150,13 +194,19 @@ LLAMA_API_URL=https://api.ag-llama.com
150
194
  LLAMA_API_KEY=llm_xxxxxxxx
151
195
  ```
152
196
 
153
- ### 3. Restart Claude
197
+ #### ChatGPT isn't supported yet
198
+
199
+ ChatGPT can only reach MCP servers over HTTPS from OpenAI's own servers — it can't spawn a local
200
+ `npx` process the way the clients above do. Connecting it would require a hosted connector, which
201
+ AG-Llama doesn't offer yet.
202
+
203
+ ### 3. Restart your client
154
204
 
155
- Restart Claude Desktop or Claude Code to load the MCP server.
205
+ Restart Claude Desktop, Claude Code, or whichever client you configured to load the MCP server.
156
206
 
157
207
  ### 4. Test the Connection
158
208
 
159
- In Claude, try:
209
+ In your AI client, try:
160
210
 
161
211
  ```
162
212
  Use llama to test the connection
@@ -172,7 +222,7 @@ You should see your user info and available organizations.
172
222
  Use llama to get the context for my-team/PROJ
173
223
  ```
174
224
 
175
- Claude will show you the active sprint, backlog, workflow statuses, and team members.
225
+ Your AI client will show you the active sprint, backlog, workflow statuses, and team members.
176
226
 
177
227
  ### Create Issues
178
228
 
@@ -210,7 +260,7 @@ Use llama to show me the board for my-team/PROJ
210
260
  Use llama to suggest a workflow for "sprint planning"
211
261
  ```
212
262
 
213
- Claude will find and execute saved workflows from your organization.
263
+ Your AI client will find and execute saved workflows from your organization.
214
264
 
215
265
  ## Available Tools
216
266
 
@@ -232,7 +282,7 @@ The MCP server provides 40+ tools organized into categories:
232
282
 
233
283
  ### Automation
234
284
  - **Search**: Find issues with filters
235
- - **Workflows**: Create and run reusable Claude workflows
285
+ - **Workflows**: Create and run reusable workflows
236
286
  - **Help**: Built-in documentation (`llama_help`)
237
287
 
238
288
  See `MCP_TOOLS.md` for the full tool reference.
@@ -242,7 +292,7 @@ See `MCP_TOOLS.md` for the full tool reference.
242
292
  | Variable | Required | Description |
243
293
  |----------|----------|-------------|
244
294
  | `LLAMA_API_URL` | Yes | API endpoint (production: `https://api.ag-llama.com`) |
245
- | `LLAMA_API_KEY` | Yes | Your API key from [AG-Llama Settings](https://agllama.onrender.com/settings/api-keys) |
295
+ | `LLAMA_API_KEY` | Yes | Your API key from [AG-Llama Profile → MCP Integration](https://agllama.onrender.com/profile) |
246
296
 
247
297
  ## Self-Hosted Setup
248
298
 
@@ -271,15 +321,15 @@ Running your own AG-Llama instance? Configure the MCP server with your local or
271
321
  ### "Connection failed" error
272
322
  - Verify your API key is correct
273
323
  - Check that `LLAMA_API_URL` is set to `https://api.ag-llama.com`
274
- - Ensure you've restarted Claude after configuration changes
324
+ - Ensure you've restarted your client after configuration changes
275
325
 
276
326
  ### "Invalid API key" error
277
- - Generate a new API key at [agllama.onrender.com/settings/api-keys](https://agllama.onrender.com/settings/api-keys)
327
+ - Generate a new API key at [agllama.onrender.com/profile](https://agllama.onrender.com/profile) → MCP Integration
278
328
  - Make sure the key starts with `llm_`
279
329
 
280
330
  ### Tools not showing up
281
- - Confirm the MCP server is configured correctly in Claude Desktop config
282
- - Check Claude's MCP server logs for errors
331
+ - Confirm the MCP server is configured correctly in your client's config
332
+ - Check your client's MCP server logs for errors
283
333
  - Try running `npx @agllama/mcp` directly to test
284
334
 
285
335
  ### Rate limiting
@@ -300,7 +350,7 @@ MIT License - see [LICENSE](LICENSE) file for details.
300
350
 
301
351
  ## Support
302
352
 
303
- - **Questions**: Use the `llama_help` tool in Claude for built-in documentation
353
+ - **Questions**: Use the `llama_help` tool in your AI client for built-in documentation
304
354
 
305
355
  ---
306
356
 
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=api-client.dispatch.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-client.dispatch.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/api-client.dispatch.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,243 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { LlamaApiClient, LlamaApiError } from '../api-client.js';
3
+ import { getApiClient, resetApiClient } from '../api-client.js';
4
+ import { runWithHostedClient } from '../hosted/context.js';
5
+ // ---------------------------------------------------------------------------
6
+ // LLAMA-2076 — proves the `LlamaTransport` injection point (api-client.ts):
7
+ // 1. Absent (default): stdio behaviour is BYTE-IDENTICAL to before this
8
+ // story — request()/getBacklog() call the real fetch().
9
+ // 2. Present: request()/getBacklog() dispatch through the injected
10
+ // function and NEVER touch fetch — this is the self-HTTP-trap fix, and
11
+ // the "escape hatch" (get/post/patch/put/delete all funnel through
12
+ // request()) comes along for free.
13
+ // 3. getApiClient() prefers the AsyncLocalStorage hosted override over the
14
+ // env-var singleton, and falls back to the singleton outside any
15
+ // runWithHostedClient() context.
16
+ // ---------------------------------------------------------------------------
17
+ describe('LlamaApiClient — transport injection (LLAMA-2076)', () => {
18
+ const fetchMock = vi.fn();
19
+ beforeEach(() => {
20
+ fetchMock.mockReset();
21
+ vi.stubGlobal('fetch', fetchMock);
22
+ });
23
+ afterEach(() => {
24
+ vi.unstubAllGlobals();
25
+ });
26
+ it('default (no transport): get() calls the real fetch(), unchanged from before this story', async () => {
27
+ fetchMock.mockResolvedValue({
28
+ status: 200,
29
+ ok: true,
30
+ json: async () => ({ success: true, data: { hello: 'world' } }),
31
+ });
32
+ const client = new LlamaApiClient('https://api.example.com', 'llm_test');
33
+ const result = await client.get('/organizations');
34
+ expect(fetchMock).toHaveBeenCalledTimes(1);
35
+ const [url, init] = fetchMock.mock.calls[0];
36
+ expect(url).toBe('https://api.example.com/api/organizations');
37
+ expect(init.method).toBe('GET');
38
+ expect(init.headers['X-API-Key']).toBe('llm_test');
39
+ expect(result).toEqual({ hello: 'world' });
40
+ });
41
+ it('with a transport injected: get() dispatches through it and NEVER calls fetch', async () => {
42
+ const transport = vi.fn(async () => ({
43
+ status: 200,
44
+ json: { success: true, data: { hello: 'hosted' } },
45
+ }));
46
+ const client = new LlamaApiClient('https://api.example.com', 'unused-in-hosted-mode', transport);
47
+ const result = await client.get('/organizations');
48
+ expect(fetchMock).not.toHaveBeenCalled();
49
+ expect(transport).toHaveBeenCalledTimes(1);
50
+ expect(transport).toHaveBeenCalledWith('GET', '/api/organizations', undefined);
51
+ expect(result).toEqual({ hello: 'hosted' });
52
+ });
53
+ it('transport-backed post()/patch()/put()/delete() all dispatch through the SAME injection point (the "escape hatch")', async () => {
54
+ const transport = vi.fn(async () => ({ status: 200, json: { success: true, data: null } }));
55
+ const client = new LlamaApiClient('https://api.example.com', 'k', transport);
56
+ await client.post('/foo', { a: 1 });
57
+ await client.patch('/foo/1', { b: 2 });
58
+ await client.put('/foo/1', { c: 3 });
59
+ await client.delete('/foo/1');
60
+ expect(fetchMock).not.toHaveBeenCalled();
61
+ expect(transport).toHaveBeenCalledTimes(4);
62
+ expect(transport).toHaveBeenNthCalledWith(1, 'POST', '/api/foo', { a: 1 });
63
+ expect(transport).toHaveBeenNthCalledWith(2, 'PATCH', '/api/foo/1', { b: 2 });
64
+ expect(transport).toHaveBeenNthCalledWith(3, 'PUT', '/api/foo/1', { c: 3 });
65
+ expect(transport).toHaveBeenNthCalledWith(4, 'DELETE', '/api/foo/1', undefined);
66
+ });
67
+ it('surfaces a transport-reported error status the same way a real fetch() error would (LlamaApiError)', async () => {
68
+ const transport = vi.fn(async () => ({
69
+ status: 404,
70
+ json: { success: false, error: 'Issue not found' },
71
+ }));
72
+ const client = new LlamaApiClient('https://api.example.com', 'k', transport);
73
+ await expect(client.get('/organizations/x/projects/y/issues/Z-1')).rejects.toMatchObject({
74
+ statusCode: 404,
75
+ message: 'Issue not found',
76
+ });
77
+ await expect(client.get('/whatever')).rejects.toBeInstanceOf(LlamaApiError);
78
+ });
79
+ it('handles a transport-reported 204 (e.g. DELETE) the same as a real 204 response', async () => {
80
+ const transport = vi.fn(async () => ({ status: 204, json: undefined }));
81
+ const client = new LlamaApiClient('https://api.example.com', 'k', transport);
82
+ const result = await client.delete('/foo/1');
83
+ expect(result).toBeUndefined();
84
+ });
85
+ it('getBacklog() also dispatches through the injected transport and never calls fetch (the raw-fetch duplicate this story found and fixed)', async () => {
86
+ const transport = vi.fn(async (_method, _path, _body) => ({
87
+ status: 200,
88
+ json: {
89
+ success: true,
90
+ data: [{ id: '1', key: 'PROJ-1', summary: 'x', type: 'STORY', priority: 'MEDIUM', status: { id: 's1', name: 'To Do', category: 'TODO', color: '#fff' } }],
91
+ pagination: { total: 42 },
92
+ },
93
+ }));
94
+ const client = new LlamaApiClient('https://api.example.com', 'k', transport);
95
+ const result = await client.getBacklog('acme', 'PROJ', 20, 0);
96
+ expect(fetchMock).not.toHaveBeenCalled();
97
+ expect(transport).toHaveBeenCalledTimes(1);
98
+ const [method, path] = transport.mock.calls[0];
99
+ expect(method).toBe('GET');
100
+ expect(path).toBe('/api/organizations/acme/projects/PROJ/backlog?limit=20&offset=0');
101
+ expect(result.total).toBe(42);
102
+ expect(result.issues).toHaveLength(1);
103
+ });
104
+ it('getBacklog() surfaces a transport error the same way the old raw-fetch duplicate did', async () => {
105
+ const transport = vi.fn(async () => ({ status: 403, json: { success: false, error: 'Not authorized' } }));
106
+ const client = new LlamaApiClient('https://api.example.com', 'k', transport);
107
+ await expect(client.getBacklog('acme', 'PROJ')).rejects.toMatchObject({
108
+ statusCode: 403,
109
+ message: 'Not authorized',
110
+ });
111
+ });
112
+ });
113
+ describe('reportError()/selfReportError() — provably inert when a transport is set (LLAMA-2076 FIX-3)', () => {
114
+ const fetchMock = vi.fn();
115
+ const ORIGINAL_KEY = process.env.ERROR_INBOX_API_KEY;
116
+ beforeEach(() => {
117
+ fetchMock.mockReset();
118
+ vi.stubGlobal('fetch', fetchMock);
119
+ // A configured error inbox key is the exact condition the review flagged
120
+ // as a latent regression: today it's unset in production, but if it were
121
+ // ever set, hosted mode must STILL never make a real self-HTTP call.
122
+ process.env.ERROR_INBOX_API_KEY = 'llm_inbox_test_key';
123
+ });
124
+ afterEach(() => {
125
+ vi.unstubAllGlobals();
126
+ if (ORIGINAL_KEY === undefined)
127
+ delete process.env.ERROR_INBOX_API_KEY;
128
+ else
129
+ process.env.ERROR_INBOX_API_KEY = ORIGINAL_KEY;
130
+ });
131
+ it('reportError() never calls fetch when a transport is set, even with ERROR_INBOX_API_KEY configured', () => {
132
+ const transport = vi.fn(async () => ({ status: 200, json: { success: true, data: null } }));
133
+ const client = new LlamaApiClient('https://api.example.com', 'unused-hosted-placeholder', transport);
134
+ client.reportError('Hosted MCP tool error', 'boom', { toolName: 'llama_get_issue' });
135
+ expect(fetchMock).not.toHaveBeenCalled();
136
+ expect(transport).not.toHaveBeenCalled();
137
+ });
138
+ it('reportError() still reports on the stdio path (no transport) with the key configured — proves the guard is transport-specific, not a global regression', () => {
139
+ fetchMock.mockResolvedValue({ status: 200, ok: true, json: async () => ({ success: true }) });
140
+ const client = new LlamaApiClient('https://api.example.com', 'llm_test'); // no transport → stdio
141
+ client.reportError('title', 'message');
142
+ expect(fetchMock).toHaveBeenCalledTimes(1);
143
+ const [url] = fetchMock.mock.calls[0];
144
+ expect(url).toBe('https://api.example.com/api/external/errors');
145
+ });
146
+ it('selfReportError() (invoked internally by request() on a 5xx) never calls fetch when a transport is set', async () => {
147
+ const transport = vi.fn(async () => ({ status: 500, json: { success: false, error: 'boom' } }));
148
+ const client = new LlamaApiClient('https://api.example.com', 'unused-hosted-placeholder', transport);
149
+ await expect(client.get('/whatever')).rejects.toMatchObject({ statusCode: 500 });
150
+ expect(fetchMock).not.toHaveBeenCalled();
151
+ });
152
+ });
153
+ describe('getApiClient() — hosted AsyncLocalStorage override takes precedence (LLAMA-2076)', () => {
154
+ const ORIGINAL_URL = process.env.LLAMA_API_URL;
155
+ const ORIGINAL_KEY = process.env.LLAMA_API_KEY;
156
+ beforeEach(() => {
157
+ resetApiClient();
158
+ process.env.LLAMA_API_URL = 'https://stdio.example.com';
159
+ process.env.LLAMA_API_KEY = 'llm_stdio_key';
160
+ });
161
+ afterEach(() => {
162
+ resetApiClient();
163
+ if (ORIGINAL_URL === undefined)
164
+ delete process.env.LLAMA_API_URL;
165
+ else
166
+ process.env.LLAMA_API_URL = ORIGINAL_URL;
167
+ if (ORIGINAL_KEY === undefined)
168
+ delete process.env.LLAMA_API_KEY;
169
+ else
170
+ process.env.LLAMA_API_KEY = ORIGINAL_KEY;
171
+ });
172
+ it('falls back to the env-var singleton outside any hosted context (stdio path, unchanged)', () => {
173
+ const client = getApiClient();
174
+ expect(client).toBe(getApiClient()); // same singleton on repeat calls
175
+ });
176
+ it('returns the ALS-bound hosted client instead of the singleton, inside runWithHostedClient()', async () => {
177
+ const stdioClient = getApiClient();
178
+ const hostedClient = new LlamaApiClient('https://api.example.com', 'unused', async () => ({
179
+ status: 200,
180
+ json: { success: true, data: null },
181
+ }));
182
+ await runWithHostedClient(hostedClient, async () => {
183
+ expect(getApiClient()).toBe(hostedClient);
184
+ expect(getApiClient()).not.toBe(stdioClient);
185
+ });
186
+ // Reverts to the singleton once the hosted context exits.
187
+ expect(getApiClient()).toBe(stdioClient);
188
+ });
189
+ });
190
+ // ---------------------------------------------------------------------------
191
+ // LLAMA-2077 REQ-08/AC08 — stdio's per-process clientSessionId identity is
192
+ // byte-for-byte unchanged by the explicit-handle story. This is the
193
+ // regression test that fails if a future change ever makes hosted mode
194
+ // (or anything else) start relying on this field, or removes it from the
195
+ // stdio X-Client-Session-Id header.
196
+ // ---------------------------------------------------------------------------
197
+ describe('LlamaApiClient — clientSessionId is untouched stdio-only identity (LLAMA-2077 REQ-08)', () => {
198
+ const fetchMock = vi.fn();
199
+ beforeEach(() => {
200
+ fetchMock.mockReset();
201
+ fetchMock.mockResolvedValue({
202
+ status: 200,
203
+ ok: true,
204
+ json: async () => ({ success: true, data: null }),
205
+ });
206
+ vi.stubGlobal('fetch', fetchMock);
207
+ });
208
+ afterEach(() => {
209
+ vi.unstubAllGlobals();
210
+ });
211
+ it('no transport (stdio): a stable per-process UUID is sent as X-Client-Session-Id on every request', async () => {
212
+ const client = new LlamaApiClient('https://api.example.com', 'llm_test');
213
+ const mintedId = client.clientSessionId;
214
+ expect(mintedId).toMatch(/^[0-9a-f-]{36}$/);
215
+ await client.get('/organizations');
216
+ await client.post('/organizations', {});
217
+ await client.get('/organizations');
218
+ expect(fetchMock).toHaveBeenCalledTimes(3);
219
+ for (const call of fetchMock.mock.calls) {
220
+ const [, init] = call;
221
+ expect(init.headers['X-Client-Session-Id']).toBe(mintedId);
222
+ }
223
+ // Same value on every call from this one process — never re-minted per request.
224
+ expect(client.clientSessionId).toBe(mintedId);
225
+ });
226
+ it('two independent LlamaApiClient instances (two stdio processes) mint two DIFFERENT clientSessionIds — never a shared/fixed value', () => {
227
+ const a = new LlamaApiClient('https://api.example.com', 'llm_a');
228
+ const b = new LlamaApiClient('https://api.example.com', 'llm_b');
229
+ expect(a.clientSessionId).not.toBe(b.clientSessionId);
230
+ });
231
+ it('with a transport injected (hosted): clientSessionId is still minted (harmless) but NEVER reaches X-Client-Session-Id — dispatch() short-circuits before the header is built', async () => {
232
+ const transport = vi.fn(async () => ({ status: 200, json: { success: true, data: null } }));
233
+ const client = new LlamaApiClient('https://api.example.com', 'unused', transport);
234
+ await client.get('/organizations');
235
+ expect(fetchMock).not.toHaveBeenCalled();
236
+ expect(transport).toHaveBeenCalledWith('GET', '/api/organizations', undefined);
237
+ // clientSessionId exists (readonly field set in the constructor) but was
238
+ // never read by the transport path — proving it structurally cannot be
239
+ // used to correlate two hosted requests, per-process or per-request.
240
+ expect(client.clientSessionId).toEqual(expect.any(String));
241
+ });
242
+ });
243
+ //# sourceMappingURL=api-client.dispatch.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-client.dispatch.test.js","sourceRoot":"","sources":["../../src/__tests__/api-client.dispatch.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,aAAa,EAA6B,MAAM,kBAAkB,CAAC;AAC5F,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE3D,8EAA8E;AAC9E,4EAA4E;AAC5E,yE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O,CAAC,CAAC;QACjE,MAAM,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC;IACxD,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,6KAA6K,EAAE,KAAK,IAAI,EAAE;QAC3L,MAAM,SAAS,GAAG,EAAE,CAAC,EAAE,CACrB,KAAK,IAAmC,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAClG,CAAC;QACF,MAAM,MAAM,GAAG,IAAI,cAAc,CAAC,yBAAyB,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;QAElF,MAAM,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;QAEnC,MAAM,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,gBAAgB,EAAE,CAAC;QACzC,MAAM,CAAC,SAAS,CAAC,CAAC,oBAAoB,CAAC,KAAK,EAAE,oBAAoB,EAAE,SAAS,CAAC,CAAC;QAC/E,yEAAyE;QACzE,uEAAuE;QACvE,qEAAqE;QACrE,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IAC7D,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -1,4 +1,31 @@
1
- import { MCPContextResponse, MCPUserInfo, MCPIssueDetail, MCPIssueSummary, MCPSprintDetail, CreateIssueInput, UpdateIssueInput, BatchCreateIssueInput, BatchUpdateIssueInput, BatchResult, CreateSprintInput, UpdateSprintInput, SearchFilters, SearchResult, MCPOrganization, CreateOrganizationInput, MCPProject, CreateProjectInput, UpdateProjectInput, MCPBoard, MoveIssueInput, MCPComment, CreateCommentInput, MCPLabel, CreateLabelInput, MCPMember, MCPIssueLink, CreateIssueLinkInput, BatchLinkIssueInput, BatchLinkResult, StartSprintInput, CompleteSprintInput, MCPSkillSummary, MCPSkillDetail, MCPSuggestedSkill, MCPSkillExecution, CreateSkillInput, UpdateSkillInput, InstallRecordResult, MCPPromptSummary, MCPPromptDetail, CreatePromptInput, UpdatePromptInput, MCPPromptFolderSummary, MCPDocumentSummary, MCPDocumentDetail, CreateDocumentInput, UpdateDocumentInput, ListDocumentsFilters, MCPColumnConfiguration, UpdateColumnConfigInput, MCPPlanSummary, MCPPlanDetail, MCPPlanFolder, MCPPlanTreeNode, CreatePlanInput, UpdatePlanInput, CreatePlanFolderInput, MCPPlanComment, McpSessionResponse, SetSessionInput, MCPAttachment, MCPProjectErrorSummary, MCPProjectErrorDetail, ListProjectErrorsParams, AcceptProjectErrorInput, MCPDecompositionDetail, CreateDecompositionInput, SubmitDecompositionAnalysisInput, ApplyDecompositionInput, ApplyDecompositionResult, MCPRoadmapSummary, MCPRoadmapDetail, LinkedClaudeSession, MCPDevLink } from './types.js';
1
+ import { MCPContextResponse, MCPUserInfo, MCPIssueDetail, MCPIssueSummary, MCPSprintDetail, CreateIssueInput, UpdateIssueInput, BatchCreateIssueInput, BatchUpdateIssueInput, BatchResult, CreateSprintInput, UpdateSprintInput, SearchFilters, SearchResult, MCPOrganization, CreateOrganizationInput, MCPProject, CreateProjectInput, UpdateProjectInput, MCPBoard, MoveIssueInput, MCPComment, CreateCommentInput, MCPLabel, CreateLabelInput, MCPMember, MCPIssueLink, CreateIssueLinkInput, BatchLinkIssueInput, BatchLinkResult, StartSprintInput, CompleteSprintInput, MCPSkillSummary, MCPSkillDetail, MCPSuggestedSkill, MCPSkillExecution, CreateSkillInput, UpdateSkillInput, InstallRecordResult, MCPPromptSummary, MCPPromptDetail, CreatePromptInput, UpdatePromptInput, MCPPromptFolderSummary, MCPDocumentSummary, MCPDocumentDetail, CreateDocumentInput, UpdateDocumentInput, ListDocumentsFilters, MCPColumnConfiguration, UpdateColumnConfigInput, MCPPlanSummary, MCPPlanDetail, MCPPlanFolder, MCPPlanTreeNode, CreatePlanInput, UpdatePlanInput, CreatePlanFolderInput, MCPPlanComment, MCPCodeDocSummary, MCPCodeDocDetail, MCPCodeDocFolder, MCPCodeDocTreeNode, CreateCodeDocInput, UpdateCodeDocInput, CreateCodeDocFolderInput, McpSessionResponse, SetSessionInput, MCPAttachment, MCPProjectErrorSummary, MCPProjectErrorDetail, ListProjectErrorsParams, AcceptProjectErrorInput, MCPDecompositionDetail, CreateDecompositionInput, SubmitDecompositionAnalysisInput, ApplyDecompositionInput, ApplyDecompositionResult, MCPRoadmapSummary, MCPRoadmapDetail, LinkedClaudeSession, MCPDevLink } from './types.js';
2
+ /**
3
+ * LLAMA-2076 — injectable transport hook for `request()`/`getBacklog()`.
4
+ *
5
+ * Absent (the default): the stdio path — Claude Code, desktop, any local
6
+ * `LlamaApiClient` — is completely unchanged; both methods fall through to
7
+ * a real `fetch()` exactly as before this story.
8
+ *
9
+ * Present (hosted mode, apps/api's `/mcp` transport route): every HTTP-shaped
10
+ * call this client makes is dispatched THROUGH the supplied function instead
11
+ * of opening a socket. This is the fix for the self-HTTP trap — hosted
12
+ * inside apps/api, a real `fetch()` back to `${baseUrl}${path}` would be the
13
+ * API calling itself over HTTP for every tool invocation, doubling request
14
+ * count and connection-pool pressure for zero benefit.
15
+ *
16
+ * The result shape — `{status, json}` — is deliberately the exact thing
17
+ * `request()` already unwraps from a real `Response`
18
+ * (`response.status` / `await response.json()`), so every existing
19
+ * success/error-surfacing branch in `request()` (and the pagination-aware
20
+ * unwrap in `getBacklog()`, which needs the raw envelope `request()`'s `T`
21
+ * narrowing would otherwise drop) is reused UNCHANGED no matter which
22
+ * transport produced the data.
23
+ */
24
+ export type LlamaTransportResult = {
25
+ status: number;
26
+ json: unknown;
27
+ };
28
+ export type LlamaTransport = (method: string, path: string, body?: unknown) => Promise<LlamaTransportResult>;
2
29
  export declare class LlamaApiError extends Error {
3
30
  statusCode: number;
4
31
  readonly details?: unknown;
@@ -8,27 +35,91 @@ export declare class LlamaApiClient {
8
35
  private baseUrl;
9
36
  private apiKey;
10
37
  private _isReportingError;
11
- /** Unique ID for this MCP server process — isolates sessions per Claude window */
38
+ /** LLAMA-2076 — see `LlamaTransport` doc comment above. */
39
+ private readonly transport?;
40
+ /**
41
+ * Unique ID for this MCP server PROCESS — isolates sessions per Claude
42
+ * window. STDIO-ONLY IDENTITY (see `dispatch()` below): sent as the
43
+ * `X-Client-Session-Id` header only on the real-`fetch()` branch, which
44
+ * `this.transport` short-circuits entirely for hosted clients. One
45
+ * stdio process = one stable UUID for its whole lifetime = correct.
46
+ *
47
+ * LLAMA-2077 — do NOT reuse this field for hosted-mode session identity.
48
+ * `mcpTransport.routes.ts` constructs a brand-new `LlamaApiClient` (and
49
+ * therefore a brand-new, immediately-discarded `clientSessionId`) once
50
+ * PER HOSTED HTTP REQUEST — a value that is never read by `dispatch()`'s
51
+ * transport branch and never transmitted anywhere (the in-process
52
+ * dispatcher's synthetic `req.headers` doesn't forward it either — see
53
+ * `expressDispatch.ts`). Hosted session identity instead uses the
54
+ * EXPLICIT-HANDLE pattern: `llama_set_context` mints an `mcp_sessions`
55
+ * row and returns its id as `sessionId` in the tool response; the model
56
+ * passes that back as an ordinary, ownership-checked tool argument on
57
+ * later calls (`tools/session.ts`, `mcp-session.service.ts`). That
58
+ * handle is keyed by (userId, mcp_sessions.id) — never by anything on
59
+ * this per-request, per-process client instance.
60
+ */
12
61
  readonly clientSessionId: string;
13
- constructor(baseUrl: string, apiKey: string);
62
+ constructor(baseUrl: string, apiKey: string, transport?: LlamaTransport);
14
63
  getAttachmentDownloadUrl(orgSlug: string, projectKey: string, issueKey: string, attachmentId: string): string;
15
64
  downloadAttachment(orgSlug: string, projectKey: string, issueKey: string, attachmentId: string): Promise<{
16
65
  buffer: Buffer;
17
66
  contentType: string;
18
67
  }>;
19
68
  private request;
69
+ /**
70
+ * The actual network call (or, when `this.transport` is set, the in-process
71
+ * hosted dispatch — see the `LlamaTransport` doc comment above). Isolated
72
+ * here so BOTH `request()` and `getBacklog()` — which historically
73
+ * duplicated this fetch logic because it needs the raw `pagination`
74
+ * envelope field `request()`'s `T` narrowing drops — share exactly ONE
75
+ * place that decides HOW a call reaches the API. Without this, overriding
76
+ * `request()` alone would leave `getBacklog()` making a real self-HTTP
77
+ * call even in hosted mode.
78
+ */
79
+ private dispatch;
20
80
  /** Returns the project-scoped error inbox key, or null if not configured. */
21
81
  private get errorInboxKey();
22
82
  /**
23
83
  * Fire-and-forget: report a 5xx from the API back to the error inbox.
24
84
  * Requires ERROR_INBOX_API_KEY env var (project-scoped key).
25
85
  * Skips if already reporting or if the failing path is the error endpoint itself.
86
+ *
87
+ * LLAMA-2076 review fix — provably inert in hosted mode (`this.transport`
88
+ * set): NOT routed through `dispatch()`/the injected transport like every
89
+ * other call, and deliberately so. `dispatch()` would take the in-process
90
+ * express path with the request's hosted OAuth identity
91
+ * (`attachTrustedIdentity` → `authMethod: 'oauth'`), but
92
+ * `/api/external/errors` (projectError.controller.ts `report()`) requires
93
+ * `authMethod === 'api_key'` with a project-scoped key — an OAuth identity
94
+ * can never satisfy that, so routing through `dispatch()` would just
95
+ * always 403 in-process: inert, but a pointless round trip that implies
96
+ * this is "supposed to work" hosted. The real bug this guards against is
97
+ * different: these two methods build their OWN raw `fetch()` using
98
+ * `ERROR_INBOX_API_KEY` (a project-scoped key with no relationship to
99
+ * `this.apiKey`/`this.transport` at all), completely bypassing the
100
+ * transport-injection point. `ERROR_INBOX_API_KEY` is unset on the API
101
+ * host today, so `errorInboxKey` already returns null and both methods
102
+ * no-op — but that makes them silently correct by accident of
103
+ * configuration, not by design. If that var were ever set there (e.g. a
104
+ * shared inbox key reused across services), hosted mode would start
105
+ * making a REAL outbound self-HTTP call on every 5xx/tool error — the
106
+ * exact self-HTTP trap this whole story exists to close (Critical
107
+ * pattern 1). Guarding on `this.transport` (only ever set for hosted
108
+ * clients — see the `LlamaTransport` doc comment above) makes that
109
+ * unreachable regardless of what `ERROR_INBOX_API_KEY` is set to.
26
110
  */
27
111
  private selfReportError;
28
112
  /**
29
113
  * Public: report an error to the project's error inbox (e.g. from tool catch blocks).
30
114
  * Requires ERROR_INBOX_API_KEY env var (project-scoped key).
31
115
  * Fire-and-forget, no-op if guard active or key not configured.
116
+ *
117
+ * LLAMA-2076 review fix — same `this.transport` guard as `selfReportError`
118
+ * above, and for the same reason (see its doc comment): provably inert in
119
+ * hosted mode no matter what `ERROR_INBOX_API_KEY` is set to on the API
120
+ * host, rather than depending on that var staying unset. `mcpTransport.routes.ts`
121
+ * calls this on every hosted tool error, so this is the exact call site
122
+ * the risk described there refers to.
32
123
  */
33
124
  reportError(title: string, message: string, metadata?: Record<string, unknown>): void;
34
125
  get<T>(path: string): Promise<T>;
@@ -224,7 +315,7 @@ export declare class LlamaApiClient {
224
315
  getBoardConfiguration(orgSlug: string, projectKey: string, boardId?: string): Promise<MCPBoard>;
225
316
  updateColumnConfiguration(orgSlug: string, projectKey: string, boardId: string, columnId: string, input: UpdateColumnConfigInput): Promise<MCPColumnConfiguration>;
226
317
  getColumnConfiguration(orgSlug: string, projectKey: string, boardId: string, columnId: string): Promise<MCPColumnConfiguration | null>;
227
- listPlans(orgSlug: string, projectKey: string, folderId?: string | null): Promise<MCPPlanSummary[]>;
318
+ listPlans(orgSlug: string, projectKey: string, folderId?: string | null, status?: string): Promise<MCPPlanSummary[]>;
228
319
  getPlanTree(orgSlug: string, projectKey: string): Promise<MCPPlanTreeNode[]>;
229
320
  getPlan(orgSlug: string, projectKey: string, planId: string): Promise<MCPPlanDetail>;
230
321
  createPlan(orgSlug: string, projectKey: string, input: CreatePlanInput): Promise<MCPPlanDetail>;
@@ -234,6 +325,15 @@ export declare class LlamaApiClient {
234
325
  listPlanFolders(orgSlug: string, projectKey: string, parentId?: string | null): Promise<MCPPlanFolder[]>;
235
326
  createPlanFolder(orgSlug: string, projectKey: string, input: CreatePlanFolderInput): Promise<MCPPlanFolder>;
236
327
  deletePlanFolder(orgSlug: string, projectKey: string, folderId: string): Promise<void>;
328
+ listCodeDocs(orgSlug: string, projectKey: string, folderId?: string | null): Promise<MCPCodeDocSummary[]>;
329
+ getCodeDocTree(orgSlug: string, projectKey: string): Promise<MCPCodeDocTreeNode[]>;
330
+ getCodeDoc(orgSlug: string, projectKey: string, docId: string): Promise<MCPCodeDocDetail>;
331
+ createCodeDoc(orgSlug: string, projectKey: string, input: CreateCodeDocInput): Promise<MCPCodeDocDetail>;
332
+ updateCodeDoc(orgSlug: string, projectKey: string, docId: string, input: UpdateCodeDocInput): Promise<MCPCodeDocDetail>;
333
+ deleteCodeDoc(orgSlug: string, projectKey: string, docId: string): Promise<void>;
334
+ searchCodeDocs(orgSlug: string, projectKey: string, query: string): Promise<MCPCodeDocSummary[]>;
335
+ createCodeDocFolder(orgSlug: string, projectKey: string, input: CreateCodeDocFolderInput): Promise<MCPCodeDocFolder>;
336
+ deleteCodeDocFolder(orgSlug: string, projectKey: string, folderId: string): Promise<void>;
237
337
  createDecomposition(orgSlug: string, projectKey: string, input: CreateDecompositionInput): Promise<MCPDecompositionDetail>;
238
338
  getDecomposition(orgSlug: string, projectKey: string, decompositionId: string): Promise<MCPDecompositionDetail>;
239
339
  submitDecompositionAnalysis(orgSlug: string, projectKey: string, decompositionId: string, input: SubmitDecompositionAnalysisInput): Promise<MCPDecompositionDetail>;