From 8b6044e10a4910f76549b45f34a1b2a760fe900e Mon Sep 17 00:00:00 2001 From: Lukas Boehler Date: Sat, 21 Nov 2026 08:18:35 +0100 Subject: [PATCH 01/11] get_session_brief: the coding-session kickoff from the Server Moved from the private archive repo (PR #116 there). Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- src/index.ts | 2 +- src/schemas/session.schema.ts | 4 + src/tools/session.tool.ts | 32 +++++++ tests/session-brief.test.mjs | 158 ++++++++++++++++++++++++++++++++++ 5 files changed, 198 insertions(+), 2 deletions(-) create mode 100644 tests/session-brief.test.mjs diff --git a/README.md b/README.md index 34a6da5..4113f1b 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,8 @@ A coding agent working a Gleap ticket names its coding session, with the `sessio Without a session id nothing changes: no header, no extra lines. +The deep link that starts a session carries only one line with the session id. The agent's first call is `get_session_brief` with that id: its result is the whole kickoff (ticket, rules, findings, repository, the Gleap plugin skill to load). A kickoff without a session id works by ticket, as before. + ## Available Tools | Tool | Description | @@ -65,12 +67,12 @@ Without a session id nothing changes: no header, no extra lines. | `get_ticket_activity_log` | Get the console logs, network requests and click trail the SDK captured with a ticket. Coding agents call it on bug reports before reproducing, to see the console errors, failed requests and the user's clicks. Headers are never returned, secrets are redacted and long logs are trimmed (errors and failed requests first); `section` and `search` narrow it | | `send_message` | Reply to a customer or add an internal note (Markdown). Agent workflows: the agent asks its operator in its own conversation (an instruction to answer or update the customer is the approval), then sends; with `sessionId` the reply is the session agent's and Gleap refuses a stale one (`stale_thread`, with the new messages) or one after a stop | | `draft_reply_to_composer` | Stage a drafted reply in the ticket's dashboard composer for a person to review, edit and send. Sends nothing. For a person's own AI client, also when a `.gleap/session.json` from another ticket is still around: Gleap refuses Kai runs and the coding session working that ticket (410), which ask their operator and send with `send_message` | +| `get_session_brief` | The kickoff of a Gleap coding session (`sessionId`, required): `GET /gleapcode/sessions/{id}/agent-brief`. The brief (ticket, ownership rules, Kai Support's findings, what an earlier session left, repository, skill and setup lines) is the first text block, then the operator feedback and the `.gleap/session.json` content; a stopped session gets only the STOP instruction. Not read-only: it hands out operator feedback, and a multi-project grant must name its project | | `report_progress` | Report the fix status on the Gleap coding session you were started from (deeplink hand-off loop; session-scoped since 2026-08), the same snapshot every runtime reports: `status` (`queued`, `working`, `needs_input`, `completed`, `failed`, `cancelled`), `step` while working (`investigating`, `reproduced`, `fixing`), a one-line `message`, `question` with `needs_input` (`kind`, `prompt`, `options`, `audience` customer or team), `customerLine` (one sentence of status the customer may read), `howSolved` (one paragraph on how the ticket was solved, sent with the last report; it feeds Kai Support's learning), `agentKind`, `agentName` and `device`. The older `phase` still works: `status` wins, and a report with only `status` also sends the phase it stands for, for a Server from before the fix status. Registers PRs (`completed` with `prUrl`) and takes the two fix messages: `customerUpdateMessage` (sent right away) and `customerShipMessage` (sent when the fix is live, by the project's post-merge setting); the result says what happened to each. The ticket is done when the customer confirms or 24 hours after the last answer without a reply, not at the merge. The result also carries `stop`, `newCustomerMessages` (see Coding sessions) and the `hook` block for `.gleap/session.json` | | `update_plan` | Live checklist on the Gleap coding session (`sessionId` or `ticketId`, like `report_progress`): the whole list each call, statuses `pending`/`in_progress`/`completed`/`cancelled` | | `wrap_up` | End-of-turn card on the session: recap, at most one question, 0-2 actions (`merge_pr`, `open_pr`, `review_changes`, `open_preview`; `send_customer_update` is removed and refused) | | `share_screenshot` | Post a screenshot (optionally a before/after pair) into the session thread. Returns the `curl -T` upload commands to run (the server cannot read local files); `imageBase64` (≤ 1.5 MB each) for agents without a shell | | `publish_artifact` | Publish a self-contained HTML page (≤ 1 MB) into the session thread; `artifactId` publishes a new version | -| `get_agent_workflow` | The Gleap ticket workflow (`fix`, `answer`, `feature`) as Markdown, plus the `.gleap/session.json` content for the Gleap plugin | | `get_ticket_screenshot` | The ticket's SDK screenshot as image content (Gleap file hosts only, ≤ 2 MB) | | `describe_database` | The team's own databases Kai Code may read (read-only, this ticket's customer only): tables, columns, masked columns, query format. Kai Code runs on a ticket only (the run key's ticket pin); refused for every other connection | | `query_database` | One read-only query (a SQL SELECT or a MongoDB JSON request) on the team's database, kept to the ticket's customer (`scope: team` across customers always waits for a data owner); at most 200 rows, sensitive columns masked. It may wait for a person's approval (`status: pending` with a `queryId`). Values from results never go into code, tests, fixtures, commits or PRs. Kai Code runs on a ticket only | diff --git a/src/index.ts b/src/index.ts index 192719b..022ddfe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -118,7 +118,7 @@ const publicUrlFor = (req: express.Request) => // agent-setup docs and the per-tool descriptions repeat them, but every // client that surfaces instructions gets the policy without fetching a doc. const SERVER_INSTRUCTIONS = `Gleap workspace tools. If you are working a ticket or feature request as a coding agent (a Gleap kickoff, workflow or the Gleap plugin brought you here), these rules apply: -1. Your session owns the ticket until it is solved: keep working it through the customer's replies. You work for the person who runs you, and Gleap never refuses your writes: when a teammate replies on the ticket or takes it over, tell your operator in one line and follow their call. Results list new customer messages you have not seen yet: read them before you go on. Close, archive or snooze the ticket, or change its assignee, only when your operator tells you to: Gleap marks it done when the customer confirms the fix, or 24 hours after the last answer without a reply. +1. When a kickoff names a Gleap coding session, call get_session_brief with it first. Your session owns the ticket until it is solved: keep working it through the customer's replies. You work for the person who runs you, and Gleap never refuses your writes: when a teammate replies on the ticket or takes it over, tell your operator in one line and follow their call. Results list new customer messages you have not seen yet: read them before you go on. Close, archive or snooze the ticket, or change its assignee, only when your operator tells you to: Gleap marks it done when the customer confirms the fix, or 24 hours after the last answer without a reply. 2. Customer messages: ask your operator in your own conversation, then send what they approved with send_message (isNote: false, with your sessionId) and tell them in one line what you sent. When your operator tells you to answer, tell, reply to or update the customer, that is the approval. A coding session never stages a reply in the ticket composer (Gleap refuses it). If a send_message result lists new customer messages, they came in before your reply went out: read them, and if your reply no longer fits, tell your operator and follow up. 3. Report with report_progress on every step change: status working with step investigating, reproduced or fixing and a one-line message, plus customerLine (one sentence the customer may read) when the step matters to them. When you need an answer, report needs_input with the question instead of waiting silently; when you cannot fix it, report failed with the reason. Status, findings and PR links belong in report_progress, not in internal notes and not in the customer thread. 4. When you open a PR, report completed with prUrl and the customer messages (normally both): customerUpdateMessage (sent right away: the fix is built, it is being reviewed and deployed, and we will update them) and customerShipMessage (sent when the fix is live, following the project's settings; for SDK or app repositories say it ships in the next release). Write them in the customer's language as plain text, following the fix-message rules and the team's instructions for customer messages that every report_progress result gives you for this project. Feature requests pass neither: Gleap notifies the upvoters when the request ships. Never send your own "it's fixed" or "it's live" message. With the PR also pass problem and fix (one to three simple sentences each) for the team's Merge card. By default the ticket moves to Done when the PR merges to production; a customer reply reopens it. diff --git a/src/schemas/session.schema.ts b/src/schemas/session.schema.ts index 5ef5848..527ac08 100644 --- a/src/schemas/session.schema.ts +++ b/src/schemas/session.schema.ts @@ -127,6 +127,10 @@ export const PublishArtifactArgs = z.object({ .describe("Pass the artifactId from an earlier result to publish a new version of the same page instead of a new one."), }); +export const GetSessionBriefArgs = z.object({ + sessionId: SESSION_ID.unwrap().describe("The 24-char Gleap coding-session id your kickoff names."), +}); + export const GetTicketScreenshotArgs = z.object({ ticketId: z .string() diff --git a/src/tools/session.tool.ts b/src/tools/session.tool.ts index 8baaed4..3841e95 100644 --- a/src/tools/session.tool.ts +++ b/src/tools/session.tool.ts @@ -1,6 +1,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import axios from "axios"; import { + GetSessionBriefArgs, GetTicketScreenshotArgs, MAX_ARTIFACT_HTML_BYTES, MAX_SHARE_BASE64_BYTES, @@ -62,6 +63,20 @@ const HOSTED_WORKFLOW: Record = { export const MAX_TICKET_SCREENSHOT_BYTES = 2_000_000; export const registerSessionTools = (server: McpServer) => { + server.registerTool( + "get_session_brief", + { + title: "Get Session Brief", + description: + "The kickoff of a Gleap coding session: the first call when a kickoff names a Gleap coding session (its sessionId). The result is the agent's kickoff: the ticket, the ownership rules, Kai Support's findings, what an earlier session left, the repository and the setup steps. The workflow itself comes from the Gleap plugin skill the brief names. The result also carries the operator's newest feedback and the session file the Gleap plugin reads. A stopped session returns only the STOP instruction.", + inputSchema: GetSessionBriefArgs.shape, + // Not read-only: Gleap hands out operator feedback once, and a + // multi-project grant must name the session's project. + annotations: { ...WRITE, idempotentHint: true }, + }, + async ({ sessionId }): Promise => getSessionBrief(sessionId), + ); + server.registerTool( "update_plan", { @@ -289,6 +304,23 @@ export const fetchWorkflow = async ( ); }; +/** The session's kickoff (GET agent-brief): the brief first, then feedback and the session file. */ +export const getSessionBrief = async (sessionId: string): Promise => { + const route = sessionRoute({ sessionId }, "agent-brief"); + if (!route) return failure("Pass sessionId: the 24-char Gleap coding-session id your kickoff names."); + const fetched = await gleapGetData(route.path); + if ("error" in fetched) return fetched.error; + const result = (fetched.data ?? {}) as Record; + const early = stoppedOrFailed(result); + if (early) return early; + const brief = typeof result.brief === "string" ? result.brief : ""; + if (!brief.trim()) return failure("Gleap returned no brief for this session."); + return withLines( + { content: [{ type: "text", text: brief }], structuredContent: result }, + [operatorFeedbackLine(result), hookLine(result)], + ); +}; + const ticketRefPath = (ticketId: string): string => encodeURIComponent(ticketId.trim().replace(/^#/, "")); /** diff --git a/tests/session-brief.test.mjs b/tests/session-brief.test.mjs new file mode 100644 index 0000000..2b3ea0a --- /dev/null +++ b/tests/session-brief.test.mjs @@ -0,0 +1,158 @@ +// get_session_brief: the kickoff of a Gleap coding session, fetched from the +// Server instead of carried in the deep link. The link names only the session; +// the brief (ticket, rules, findings, repository) comes from +// GET /gleapcode/sessions/{id}/agent-brief. +import assert from 'node:assert/strict'; +import { beforeEach, describe, test } from 'node:test'; +import axios from 'axios'; +import { z } from 'zod'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; + +process.env.GLEAP_API_BASE = 'https://gleap-api.invalid/v3'; +const { registerSessionTools } = await import('../build/tools/session.tool.js'); +const { runWithCreds } = await import('../build/utils/credentials.js'); +const { applySessionScopePolicy } = await import('../build/utils/sessionScope.js'); +const { applyProjectSelection, registerProjectTools } = await import('../build/utils/projectSelection.js'); +const { STOP_TEXT } = await import('../build/utils/agentSession.js'); + +const tools = new Map(); +const registry = { + registerTool(name, config, handler) { tools.set(name, { config, handler }); }, + registerPrompt() {}, +}; +applySessionScopePolicy(registry); +registerSessionTools(registry); + +const PROJECT = '613b5dd730aed737108f87ab'; +const SESSION = '64f0c0ffee0000000000abcd'; +const STOPPED = '64f0c0ffee0000000000dead'; +const BRIEF = '# Fix ticket #7\nYour session owns ticket #7. Repository: GleapSDK/Frontend. Load the Gleap plugin skill fix-ticket.'; +const HOOK = { sessionId: SESSION, token: 'hook-jwt-secret', apiBase: 'https://api.gleap.io/v3', expiresAt: '2026-11-14T12:00:00Z' }; + +let requests; +const header = (headers, name) => headers?.[name] ?? headers?.get?.(name); +beforeEach(() => { + requests = []; + axios.defaults.adapter = async (config) => { + requests.push({ method: config.method, url: config.url, params: config.params, headers: config.headers }); + const ok = (data) => ({ data, status: 200, statusText: 'OK', headers: {}, config }); + if (config.url.endsWith(`/gleapcode/sessions/${STOPPED}/agent-brief`)) { + return ok({ success: true, sessionId: STOPPED, stop: true, kind: 'fix', brief: '' }); + } + if (config.url.endsWith(`/gleapcode/sessions/${SESSION}/agent-brief`)) { + return ok({ + success: true, + sessionId: SESSION, + stop: false, + hook: HOOK, + kind: 'fix', + brief: BRIEF, + operatorFeedback: { message: 'Your operator asked for changes: keep the old button label.' }, + }); + } + throw new axios.AxiosError('Not found', 'ERR_BAD_REQUEST', config, null, { data: { message: 'Not found' }, status: 404, statusText: 'Not Found', headers: {}, config }); + }; +}); + +const call = (args) => runWithCreds({ apiKey: 'test-only', projectId: PROJECT }, async () => { + const { config, handler } = tools.get('get_session_brief'); + return handler(z.object(config.inputSchema).strict().parse(args)); +}); + +describe('get_session_brief', () => { + test('is registered with the get_agent_workflow annotations and a description under 1024 chars', () => { + const { config } = tools.get('get_session_brief'); + assert.deepEqual(config.annotations, { readOnlyHint: false, destructiveHint: false, openWorldHint: false, idempotentHint: true }); + assert.ok(config.description.length <= 1024, `description is ${config.description.length} chars`); + assert.match(config.description, /get_session_brief|kickoff/); + }); + + test('GETs the session\'s agent-brief with the caller\'s project', async () => { + await call({ sessionId: SESSION }); + assert.equal(requests.length, 1); + assert.equal(requests[0].method, 'get'); + assert.equal(new URL(requests[0].url).pathname, `/v3/gleapcode/sessions/${SESSION}/agent-brief`); + assert.equal(header(requests[0].headers, 'project'), PROJECT); + }); + + test('the brief comes first, then the operator feedback and the session file', async () => { + const res = await call({ sessionId: SESSION }); + assert.equal(res.isError, undefined); + assert.equal(res.content[0].text, BRIEF); + assert.ok(!res.content[0].text.includes(HOOK.token), 'the token is not in the brief block'); + const texts = res.content.map((c) => c.text); + assert.ok(texts.includes('Your operator asked for changes: keep the old button label.')); + const hook = texts.find((t) => t.includes('.gleap/session.json')); + assert.ok(hook, 'hook line present'); + assert.ok(hook.includes(HOOK.token)); + assert.ok(texts.indexOf(hook) > 0); + assert.equal(res.structuredContent.sessionId, SESSION); + assert.equal(res.structuredContent.kind, 'fix'); + }); + + test('a stopped session gets only the STOP instruction', async () => { + const res = await call({ sessionId: STOPPED }); + assert.equal(res.content.length, 1); + assert.equal(res.content[0].text, STOP_TEXT); + assert.equal(res.structuredContent.stop, true); + }); + + test('another project\'s session comes back as an error', async () => { + const res = await call({ sessionId: '64f0c0ffee0000000000ffff' }); + assert.equal(res.isError, true); + assert.match(res.content[0].text, /404/); + }); + + test('sessionId is required and must be a session id: refused before any request', async () => { + const schema = z.object(tools.get('get_session_brief').config.inputSchema).strict(); + assert.throws(() => schema.parse({})); + assert.throws(() => schema.parse({ sessionId: '../../tickets/x' })); + assert.throws(() => schema.parse({ sessionId: `${SESSION}/../x` })); + // The handler itself refuses too (a client that skips the schema). + const res = await runWithCreds({ apiKey: 'test-only', projectId: PROJECT }, () => + tools.get('get_session_brief').handler({ sessionId: '../x' })); + assert.equal(res.isError, true); + assert.equal(requests.length, 0); + }); +}); + +describe('get_session_brief on a multi-project connection', () => { + const GLEAP = { projectId: '64a000000000000000000001', name: 'Gleap', apiKey: 'key-gleap' }; + const ACME = { projectId: '64a000000000000000000002', name: 'Acme Web', apiKey: 'key-acme' }; + const PROJECTS = [GLEAP, ACME]; + const multi = { apiKey: GLEAP.apiKey, projectId: GLEAP.projectId, projects: PROJECTS }; + + const connect = async () => { + const server = new McpServer({ name: 'gleap-mcp-test', version: '0.0.0' }); + applyProjectSelection(server, PROJECTS); + registerProjectTools(server, PROJECTS); + applySessionScopePolicy(server); + registerSessionTools(server); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: 'test-client', version: '0.0.0' }); + await server.connect(serverTransport); + await client.connect(clientTransport); + return client; + }; + + test('without projectId -> refused before any request (the call consumes operator words)', async () => { + const client = await connect(); + const res = await runWithCreds(multi, () => client.callTool({ name: 'get_session_brief', arguments: { sessionId: SESSION } })); + assert.equal(res.isError, true); + assert.match(res.content[0].text, /needs projectId/); + assert.equal(requests.length, 0); + }); + + test('naming a project -> that project\'s key', async () => { + const client = await connect(); + const res = await runWithCreds(multi, () => + client.callTool({ name: 'get_session_brief', arguments: { sessionId: SESSION, projectId: ACME.projectId } })); + assert.notEqual(res.isError, true); + assert.equal(res.content[0].text, BRIEF); + assert.equal(requests.length, 1); + assert.equal(header(requests[0].headers, 'project'), ACME.projectId); + assert.equal(header(requests[0].headers, 'Authorization'), `Bearer ${ACME.apiKey}`); + }); +}); From 854aa2628fb01d4e22ded308a3815d0b0c271508 Mon Sep 17 00:00:00 2001 From: LucaB01 Date: Wed, 18 Nov 2026 16:06:46 +0100 Subject: [PATCH 02/11] test(session): get_session_brief reads the brief from the Server's agent-workflow route The Server serves a session's brief on GET /gleapcode/sessions/{id}/agent-workflow without a kind, as Markdown in `markdown` (`brief` is its structured form). There is no agent-brief route. The required behaviour changed, so this test changes. Co-Authored-By: Claude Opus 5.5 --- tests/session-brief.test.mjs | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/tests/session-brief.test.mjs b/tests/session-brief.test.mjs index 2b3ea0a..de8f56e 100644 --- a/tests/session-brief.test.mjs +++ b/tests/session-brief.test.mjs @@ -1,7 +1,9 @@ // get_session_brief: the kickoff of a Gleap coding session, fetched from the // Server instead of carried in the deep link. The link names only the session; // the brief (ticket, rules, findings, repository) comes from -// GET /gleapcode/sessions/{id}/agent-brief. +// GET /gleapcode/sessions/{id}/agent-workflow without a kind: the Server picks +// the session's own kind and returns the brief as Markdown in `markdown` +// (`brief` is its structured form). import assert from 'node:assert/strict'; import { beforeEach, describe, test } from 'node:test'; import axios from 'axios'; @@ -28,6 +30,7 @@ registerSessionTools(registry); const PROJECT = '613b5dd730aed737108f87ab'; const SESSION = '64f0c0ffee0000000000abcd'; const STOPPED = '64f0c0ffee0000000000dead'; +const BRIEF_FIELDS = { ticket: { bugId: 7 }, repository: 'GleapSDK/Frontend', skill: 'fix-ticket' }; const BRIEF = '# Fix ticket #7\nYour session owns ticket #7. Repository: GleapSDK/Frontend. Load the Gleap plugin skill fix-ticket.'; const HOOK = { sessionId: SESSION, token: 'hook-jwt-secret', apiBase: 'https://api.gleap.io/v3', expiresAt: '2026-11-14T12:00:00Z' }; @@ -38,17 +41,18 @@ beforeEach(() => { axios.defaults.adapter = async (config) => { requests.push({ method: config.method, url: config.url, params: config.params, headers: config.headers }); const ok = (data) => ({ data, status: 200, statusText: 'OK', headers: {}, config }); - if (config.url.endsWith(`/gleapcode/sessions/${STOPPED}/agent-brief`)) { - return ok({ success: true, sessionId: STOPPED, stop: true, kind: 'fix', brief: '' }); + if (config.url.endsWith(`/gleapcode/sessions/${STOPPED}/agent-workflow`)) { + return ok({ success: true, sessionId: STOPPED, stop: true, kind: 'fix', brief: BRIEF_FIELDS, markdown: BRIEF }); } - if (config.url.endsWith(`/gleapcode/sessions/${SESSION}/agent-brief`)) { + if (config.url.endsWith(`/gleapcode/sessions/${SESSION}/agent-workflow`)) { return ok({ success: true, sessionId: SESSION, stop: false, hook: HOOK, kind: 'fix', - brief: BRIEF, + brief: BRIEF_FIELDS, + markdown: BRIEF, operatorFeedback: { message: 'Your operator asked for changes: keep the old button label.' }, }); } @@ -69,11 +73,13 @@ describe('get_session_brief', () => { assert.match(config.description, /get_session_brief|kickoff/); }); - test('GETs the session\'s agent-brief with the caller\'s project', async () => { + test('GETs the session\'s agent-workflow without a kind, with the caller\'s project', async () => { await call({ sessionId: SESSION }); assert.equal(requests.length, 1); assert.equal(requests[0].method, 'get'); - assert.equal(new URL(requests[0].url).pathname, `/v3/gleapcode/sessions/${SESSION}/agent-brief`); + assert.equal(new URL(requests[0].url).pathname, `/v3/gleapcode/sessions/${SESSION}/agent-workflow`); + assert.equal(requests[0].params?.kind, undefined); + assert.equal(new URL(requests[0].url).searchParams.has('kind'), false); assert.equal(header(requests[0].headers, 'project'), PROJECT); }); From 8b469ed943b1ad12c9ede105aa40533aab445c36 Mon Sep 17 00:00:00 2001 From: LucaB01 Date: Wed, 18 Nov 2026 16:07:10 +0100 Subject: [PATCH 03/11] fix(session): get_session_brief reads the Server's agent-workflow route The Server has no agent-brief route: it serves a session's brief on GET /gleapcode/sessions/{id}/agent-workflow without a kind, as Markdown in `markdown`. get_session_brief now calls that route and returns that text. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/tools/session.tool.ts | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4113f1b..63c0d59 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ The deep link that starts a session carries only one line with the session id. T | `get_ticket_activity_log` | Get the console logs, network requests and click trail the SDK captured with a ticket. Coding agents call it on bug reports before reproducing, to see the console errors, failed requests and the user's clicks. Headers are never returned, secrets are redacted and long logs are trimmed (errors and failed requests first); `section` and `search` narrow it | | `send_message` | Reply to a customer or add an internal note (Markdown). Agent workflows: the agent asks its operator in its own conversation (an instruction to answer or update the customer is the approval), then sends; with `sessionId` the reply is the session agent's and Gleap refuses a stale one (`stale_thread`, with the new messages) or one after a stop | | `draft_reply_to_composer` | Stage a drafted reply in the ticket's dashboard composer for a person to review, edit and send. Sends nothing. For a person's own AI client, also when a `.gleap/session.json` from another ticket is still around: Gleap refuses Kai runs and the coding session working that ticket (410), which ask their operator and send with `send_message` | -| `get_session_brief` | The kickoff of a Gleap coding session (`sessionId`, required): `GET /gleapcode/sessions/{id}/agent-brief`. The brief (ticket, ownership rules, Kai Support's findings, what an earlier session left, repository, skill and setup lines) is the first text block, then the operator feedback and the `.gleap/session.json` content; a stopped session gets only the STOP instruction. Not read-only: it hands out operator feedback, and a multi-project grant must name its project | +| `get_session_brief` | The kickoff of a Gleap coding session (`sessionId`, required): `GET /gleapcode/sessions/{id}/agent-workflow` without a kind, which returns the brief as Markdown. The brief (ticket, ownership rules, Kai Support's findings, what an earlier session left, repository, skill and setup lines) is the first text block, then the operator feedback and the `.gleap/session.json` content; a stopped session gets only the STOP instruction. Not read-only: it hands out operator feedback, and a multi-project grant must name its project | | `report_progress` | Report the fix status on the Gleap coding session you were started from (deeplink hand-off loop; session-scoped since 2026-08), the same snapshot every runtime reports: `status` (`queued`, `working`, `needs_input`, `completed`, `failed`, `cancelled`), `step` while working (`investigating`, `reproduced`, `fixing`), a one-line `message`, `question` with `needs_input` (`kind`, `prompt`, `options`, `audience` customer or team), `customerLine` (one sentence of status the customer may read), `howSolved` (one paragraph on how the ticket was solved, sent with the last report; it feeds Kai Support's learning), `agentKind`, `agentName` and `device`. The older `phase` still works: `status` wins, and a report with only `status` also sends the phase it stands for, for a Server from before the fix status. Registers PRs (`completed` with `prUrl`) and takes the two fix messages: `customerUpdateMessage` (sent right away) and `customerShipMessage` (sent when the fix is live, by the project's post-merge setting); the result says what happened to each. The ticket is done when the customer confirms or 24 hours after the last answer without a reply, not at the merge. The result also carries `stop`, `newCustomerMessages` (see Coding sessions) and the `hook` block for `.gleap/session.json` | | `update_plan` | Live checklist on the Gleap coding session (`sessionId` or `ticketId`, like `report_progress`): the whole list each call, statuses `pending`/`in_progress`/`completed`/`cancelled` | | `wrap_up` | End-of-turn card on the session: recap, at most one question, 0-2 actions (`merge_pr`, `open_pr`, `review_changes`, `open_preview`; `send_customer_update` is removed and refused) | diff --git a/src/tools/session.tool.ts b/src/tools/session.tool.ts index 3841e95..b0c4c03 100644 --- a/src/tools/session.tool.ts +++ b/src/tools/session.tool.ts @@ -304,16 +304,19 @@ export const fetchWorkflow = async ( ); }; -/** The session's kickoff (GET agent-brief): the brief first, then feedback and the session file. */ +/** + * The session's kickoff: GET agent-workflow without a kind, so the Server picks the session's own + * kind and returns the brief as Markdown (`markdown`; `brief` is its structured form). + */ export const getSessionBrief = async (sessionId: string): Promise => { - const route = sessionRoute({ sessionId }, "agent-brief"); + const route = sessionRoute({ sessionId }, "agent-workflow"); if (!route) return failure("Pass sessionId: the 24-char Gleap coding-session id your kickoff names."); const fetched = await gleapGetData(route.path); if ("error" in fetched) return fetched.error; const result = (fetched.data ?? {}) as Record; const early = stoppedOrFailed(result); if (early) return early; - const brief = typeof result.brief === "string" ? result.brief : ""; + const brief = typeof result.markdown === "string" ? result.markdown : ""; if (!brief.trim()) return failure("Gleap returned no brief for this session."); return withLines( { content: [{ type: "text", text: brief }], structuredContent: result }, From 230dfd135e022c3410d357c630be23913e096480 Mon Sep 17 00:00:00 2001 From: LucaB01 Date: Wed, 18 Nov 2026 16:06:28 +0100 Subject: [PATCH 04/11] test(session): get_session_brief imports the TypeScript sources, as main's tests do Co-Authored-By: Claude Opus 5.5 --- tests/session-brief.test.mjs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/session-brief.test.mjs b/tests/session-brief.test.mjs index de8f56e..4fbd300 100644 --- a/tests/session-brief.test.mjs +++ b/tests/session-brief.test.mjs @@ -13,11 +13,11 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; process.env.GLEAP_API_BASE = 'https://gleap-api.invalid/v3'; -const { registerSessionTools } = await import('../build/tools/session.tool.js'); -const { runWithCreds } = await import('../build/utils/credentials.js'); -const { applySessionScopePolicy } = await import('../build/utils/sessionScope.js'); -const { applyProjectSelection, registerProjectTools } = await import('../build/utils/projectSelection.js'); -const { STOP_TEXT } = await import('../build/utils/agentSession.js'); +const { registerSessionTools } = await import('../src/tools/session.tool.js'); +const { runWithCreds } = await import('../src/utils/credentials.js'); +const { applySessionScopePolicy } = await import('../src/utils/sessionScope.js'); +const { applyProjectSelection, registerProjectTools } = await import('../src/utils/projectSelection.js'); +const { STOP_TEXT } = await import('../src/utils/agentSession.js'); const tools = new Map(); const registry = { From 69f930270db44e6186420659882e92912e297a57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20B=C3=B6hler?= Date: Mon, 23 Nov 2026 21:58:35 +0100 Subject: [PATCH 05/11] fix: instructions match the Server, a code-fix session never writes to the customer Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- src/index.ts | 4 ++-- tests/mcp-endpoint.test.ts | 12 ++++++++++++ 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 63c0d59..c3b48cf 100644 --- a/README.md +++ b/README.md @@ -65,8 +65,8 @@ The deep link that starts a session carries only one line with the session id. T | `get_ticket_types` | List ticket types with their custom fields, status lanes and priorities | | `get_ticket_messages` | Get the full conversation history (messages) for a ticket | | `get_ticket_activity_log` | Get the console logs, network requests and click trail the SDK captured with a ticket. Coding agents call it on bug reports before reproducing, to see the console errors, failed requests and the user's clicks. Headers are never returned, secrets are redacted and long logs are trimmed (errors and failed requests first); `section` and `search` narrow it | -| `send_message` | Reply to a customer or add an internal note (Markdown). Agent workflows: the agent asks its operator in its own conversation (an instruction to answer or update the customer is the approval), then sends; with `sessionId` the reply is the session agent's and Gleap refuses a stale one (`stale_thread`, with the new messages) or one after a stop | -| `draft_reply_to_composer` | Stage a drafted reply in the ticket's dashboard composer for a person to review, edit and send. Sends nothing. For a person's own AI client, also when a `.gleap/session.json` from another ticket is still around: Gleap refuses Kai runs and the coding session working that ticket (410), which ask their operator and send with `send_message` | +| `send_message` | Reply to a customer or add an internal note (Markdown). A session started from a ticket's code fix never sends to the customer (Gleap refuses it; it drafts in `report_progress`). Other agent workflows: the agent asks its operator in its own conversation (an instruction to answer or update the customer is the approval), then sends; with `sessionId` the reply is the session agent's and Gleap refuses a stale one (`stale_thread`, with the new messages) or one after a stop | +| `draft_reply_to_composer` | Stage a drafted reply in the ticket's dashboard composer for a person to review, edit and send. Sends nothing. For a person's own AI client, also when a `.gleap/session.json` from another ticket is still around: Gleap refuses Kai runs and the coding session working that ticket (410): Kai runs ask their operator and send with `send_message`, a code-fix session drafts in `report_progress` | | `get_session_brief` | The kickoff of a Gleap coding session (`sessionId`, required): `GET /gleapcode/sessions/{id}/agent-workflow` without a kind, which returns the brief as Markdown. The brief (ticket, ownership rules, Kai Support's findings, what an earlier session left, repository, skill and setup lines) is the first text block, then the operator feedback and the `.gleap/session.json` content; a stopped session gets only the STOP instruction. Not read-only: it hands out operator feedback, and a multi-project grant must name its project | | `report_progress` | Report the fix status on the Gleap coding session you were started from (deeplink hand-off loop; session-scoped since 2026-08), the same snapshot every runtime reports: `status` (`queued`, `working`, `needs_input`, `completed`, `failed`, `cancelled`), `step` while working (`investigating`, `reproduced`, `fixing`), a one-line `message`, `question` with `needs_input` (`kind`, `prompt`, `options`, `audience` customer or team), `customerLine` (one sentence of status the customer may read), `howSolved` (one paragraph on how the ticket was solved, sent with the last report; it feeds Kai Support's learning), `agentKind`, `agentName` and `device`. The older `phase` still works: `status` wins, and a report with only `status` also sends the phase it stands for, for a Server from before the fix status. Registers PRs (`completed` with `prUrl`) and takes the two fix messages: `customerUpdateMessage` (sent right away) and `customerShipMessage` (sent when the fix is live, by the project's post-merge setting); the result says what happened to each. The ticket is done when the customer confirms or 24 hours after the last answer without a reply, not at the merge. The result also carries `stop`, `newCustomerMessages` (see Coding sessions) and the `hook` block for `.gleap/session.json` | | `update_plan` | Live checklist on the Gleap coding session (`sessionId` or `ticketId`, like `report_progress`): the whole list each call, statuses `pending`/`in_progress`/`completed`/`cancelled` | diff --git a/src/index.ts b/src/index.ts index 022ddfe..6c7aa6e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -118,8 +118,8 @@ const publicUrlFor = (req: express.Request) => // agent-setup docs and the per-tool descriptions repeat them, but every // client that surfaces instructions gets the policy without fetching a doc. const SERVER_INSTRUCTIONS = `Gleap workspace tools. If you are working a ticket or feature request as a coding agent (a Gleap kickoff, workflow or the Gleap plugin brought you here), these rules apply: -1. When a kickoff names a Gleap coding session, call get_session_brief with it first. Your session owns the ticket until it is solved: keep working it through the customer's replies. You work for the person who runs you, and Gleap never refuses your writes: when a teammate replies on the ticket or takes it over, tell your operator in one line and follow their call. Results list new customer messages you have not seen yet: read them before you go on. Close, archive or snooze the ticket, or change its assignee, only when your operator tells you to: Gleap marks it done when the customer confirms the fix, or 24 hours after the last answer without a reply. -2. Customer messages: ask your operator in your own conversation, then send what they approved with send_message (isNote: false, with your sessionId) and tell them in one line what you sent. When your operator tells you to answer, tell, reply to or update the customer, that is the approval. A coding session never stages a reply in the ticket composer (Gleap refuses it). If a send_message result lists new customer messages, they came in before your reply went out: read them, and if your reply no longer fits, tell your operator and follow up. +1. When a kickoff names a Gleap coding session, call get_session_brief with it first. A session started from a ticket's code fix owns the ticket until its pull request is open, then Operator has it again; otherwise your session owns it until it is solved. You work for the person who runs you: when a teammate replies on the ticket or takes it over, tell your operator in one line and follow their call. Results list new customer messages you have not seen yet: read them before you go on. Close, archive or snooze the ticket, or change its assignee, only when your operator tells you to: Gleap marks it done when the customer confirms the fix, or 24 hours after the last answer without a reply. +2. Customer messages: a session started from a ticket's code fix never sends anything to the customer (Gleap refuses its send_message): it reports with report_progress, drafts in customerLine, customerUpdateMessage and customerShipMessage, and Kai tells the customer. Otherwise (your own AI client on a ticket): ask your operator in your own conversation, then send what they approved with send_message (isNote: false, with your sessionId) and tell them in one line what you sent. When your operator tells you to answer, tell, reply to or update the customer, that is the approval. A coding session never stages a reply in the ticket composer (Gleap refuses it). If a send_message result lists new customer messages, they came in before your reply went out: read them, and if your reply no longer fits, tell your operator and follow up. 3. Report with report_progress on every step change: status working with step investigating, reproduced or fixing and a one-line message, plus customerLine (one sentence the customer may read) when the step matters to them. When you need an answer, report needs_input with the question instead of waiting silently; when you cannot fix it, report failed with the reason. Status, findings and PR links belong in report_progress, not in internal notes and not in the customer thread. 4. When you open a PR, report completed with prUrl and the customer messages (normally both): customerUpdateMessage (sent right away: the fix is built, it is being reviewed and deployed, and we will update them) and customerShipMessage (sent when the fix is live, following the project's settings; for SDK or app repositories say it ships in the next release). Write them in the customer's language as plain text, following the fix-message rules and the team's instructions for customer messages that every report_progress result gives you for this project. Feature requests pass neither: Gleap notifies the upvoters when the request ships. Never send your own "it's fixed" or "it's live" message. With the PR also pass problem and fix (one to three simple sentences each) for the team's Merge card. By default the ticket moves to Done when the PR merges to production; a customer reply reopens it. 5. When the ticket is solved, end with report_progress and howSolved: one paragraph on how it was solved (the cause, what changed or what you answered, how you checked it), with no customer data; it feeds Kai Support's learning. Work visibly in the Gleap session: keep a plan with update_plan for any task with more than two steps; after you checked a user-visible change, share_screenshot 1-3 screenshots with a one-line caption; use publish_artifact for reports, mockups or anything easier to read as a page; end EVERY turn with wrap_up (recap first, then at most one question with one or two actions, recommended first). When a result gives you the .gleap/session.json content, write it and add .gleap/ to .git/info/exclude. diff --git a/tests/mcp-endpoint.test.ts b/tests/mcp-endpoint.test.ts index fea9683..44c68f5 100644 --- a/tests/mcp-endpoint.test.ts +++ b/tests/mcp-endpoint.test.ts @@ -152,6 +152,18 @@ describe('API key headers', () => { await client.close(); }); + test("the instructions match the Server's code-fix rule: such a session never writes to the customer", async () => { + const client = await connect(apiKeyHeaders()); + const instructions = client.getInstructions() ?? ''; + await client.close(); + assert.doesNotMatch(instructions, /never refuses your writes/); + // A session started from a ticket's code fix reports and drafts; Kai tells the customer. + assert.match(instructions, /code fix[^\n]*never send(s)? (anything )?to the customer/i); + assert.match(instructions, /customerUpdateMessage/); + // A person's own AI client working a ticket outside a code fix still asks its operator, then sends. + assert.match(instructions, /ask your operator[^\n]*send_message/i); + }); + test('concurrent clients each get their own project, never another one', async () => { gleapApi.answerWith((request) => ({ status: 200, data: [{ _id: request.headers.project, name: `team of ${request.headers.project}` }] })); const projects = Array.from({ length: 12 }, (_, i) => `project-${i}`); From 5fd32c3cfc2f1936748d0a665fe0d93305046d39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20B=C3=B6hler?= Date: Wed, 25 Nov 2026 12:54:45 +0100 Subject: [PATCH 06/11] feat(progress): antigravity as a report_progress agentKind Co-Authored-By: Claude Opus 5.5 --- src/schemas/progress.schema.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/schemas/progress.schema.ts b/src/schemas/progress.schema.ts index d5d58c6..9b70bfd 100644 --- a/src/schemas/progress.schema.ts +++ b/src/schemas/progress.schema.ts @@ -13,7 +13,7 @@ export const FIX_STATUSES = ["queued", "working", "needs_input", "completed", "f export const FIX_STEPS = ["investigating", "reproduced", "fixing"] as const; export const QUESTION_KINDS = ["question", "approval", "auth", "choice"] as const; export const QUESTION_AUDIENCES = ["customer", "team"] as const; -export const AGENT_KINDS = ["claude_code", "codex", "cursor", "other"] as const; +export const AGENT_KINDS = ["claude_code", "codex", "cursor", "antigravity", "other"] as const; export const AGENT_PHASES = ["investigating", "reproduced", "fixing", "pr_opened", "blocked", "done"] as const; export const ReportProgressArgs = z.object({ @@ -83,7 +83,7 @@ export const ReportProgressArgs = z.object({ agentKind: z .enum(AGENT_KINDS) .optional() - .describe("Which coding agent you are: claude_code, codex, cursor, or other (then name yourself in agentName). Tags the session and every message you write. Send it on every report."), + .describe("Which coding agent you are: claude_code, codex, cursor, antigravity, or other (then name yourself in agentName). Tags the session and every message you write. Send it on every report."), agentName: z .string() .max(60) From dc905c990360a4a473f9dbd03e165da17c82c5c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20B=C3=B6hler?= Date: Sat, 28 Nov 2026 20:28:36 +0100 Subject: [PATCH 07/11] feat(operator): solve_ticket prompt, session rules defer to the brief The instruction text and five tool texts no longer state their own rule for customer messages and ticket ownership: they point at the session's brief and fall back to asking first. Co-Authored-By: Claude Fable 5.2 --- README.md | 2 +- src/index.ts | 4 ++-- src/prompts/ticket.prompts.ts | 24 +++++++++++++++++++++--- src/schemas/progress.schema.ts | 2 +- src/schemas/session.schema.ts | 2 +- src/tools/message.tool.ts | 4 ++-- src/tools/session.tool.ts | 2 +- 7 files changed, 29 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 4610269..b6fa653 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ Error results set `isError: true`. Reads retry transient API failures (5xx, 429, ## Prompts and MCP Apps view -- Prompts `fix_ticket` and `answer_ticket` (argument `ticket`: `#number` or id) start a ticket workflow with the workflow text and a ticket summary. +- Prompts `fix_ticket`, `answer_ticket` and `solve_ticket` (argument `ticket`: `#number` or id) start a ticket workflow with the workflow text and a ticket summary. - `update_plan`, `wrap_up`, `share_screenshot` and `publish_artifact` carry `_meta.ui.resourceUri = "ui://gleap/kai-session"`: hosts that support [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) render the result inline from `structuredContent.view`; every other client reads the text content. ## Examples diff --git a/src/index.ts b/src/index.ts index a1f131a..4bb400e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -119,8 +119,8 @@ const publicUrlFor = (req: express.Request) => // agent-setup docs and the per-tool descriptions repeat them, but every // client that surfaces instructions gets the policy without fetching a doc. const SERVER_INSTRUCTIONS = `Gleap workspace tools. If you are working a ticket or feature request as a coding agent (a Gleap kickoff, workflow or the Gleap plugin brought you here), these rules apply: -1. Your session owns the ticket until it is solved: keep working it through the customer's replies. You work for the person who runs you, and Gleap never refuses your writes: when a teammate replies on the ticket or takes it over, tell your operator in one line and follow their call. Results list new customer messages you have not seen yet: read them before you go on. Close, archive or snooze the ticket, or change its assignee, only when your operator tells you to: Gleap marks it done when the customer confirms the fix, or 24 hours after the last answer without a reply. -2. Customer messages: ask your operator in your own conversation, then send what they approved with send_message (isNote: false, with your sessionId) and tell them in one line what you sent. When your operator tells you to answer, tell, reply to or update the customer, that is the approval. A coding session never stages a reply in the ticket composer (Gleap refuses it). If a send_message result lists new customer messages, they came in before your reply went out: read them, and if your reply no longer fits, tell your operator and follow up. +1. Your session's brief (your kickoff, or the rules a Gleap ticket prompt or workflow gave you) says how long your session owns the ticket and whether it writes to the customer: where it says so, it wins over these rules. Otherwise your session owns the ticket until it is solved: keep working it through the customer's replies. You work for the person who runs you: when a teammate replies on the ticket or takes it over, tell your operator in one line and follow their call. Results list new customer messages you have not seen yet: read them before you go on. Close, archive or snooze the ticket, or change its assignee, only when your operator tells you to: Gleap marks it done when the customer confirms the fix, or 24 hours after the last answer without a reply. +2. Customer messages: your brief says whether you send them yourself or ask your operator first. When it says neither, ask your operator in your own conversation, then send what they approved with send_message (isNote: false, with your sessionId) and tell them in one line what you sent. When your operator tells you to answer, tell, reply to or update the customer, that is the approval. A coding session never stages a reply in the ticket composer (Gleap refuses it). If a send_message result lists new customer messages, they came in before your reply went out: read them, and if your reply no longer fits, tell your operator and follow up. A result that says STOP ends your writes to the ticket: tell your operator in one line. 3. Report with report_progress on every step change: status working with step investigating, reproduced or fixing and a one-line message, plus customerLine (one sentence the customer may read) when the step matters to them. When you need an answer, report needs_input with the question instead of waiting silently; when you cannot fix it, report failed with the reason. Status, findings and PR links belong in report_progress, not in internal notes and not in the customer thread. 4. When you open a PR, report completed with prUrl and the customer messages (normally both): customerUpdateMessage (sent right away: the fix is built, it is being reviewed and deployed, and we will update them) and customerShipMessage (sent when the fix is live, following the project's settings; for SDK or app repositories say it ships in the next release). Write them in the customer's language as plain text, following the fix-message rules and the team's instructions for customer messages that every report_progress result gives you for this project. Feature requests pass neither: Gleap notifies the upvoters when the request ships. Never send your own "it's fixed" or "it's live" message. With the PR also pass problem and fix (one to three simple sentences each) for the team's Merge card. By default the ticket moves to Done when the PR merges to production; a customer reply reopens it. 5. When the ticket is solved, end with report_progress and howSolved: one paragraph on how it was solved (the cause, what changed or what you answered, how you checked it), with no customer data; it feeds Kai Support's learning. Work visibly in the Gleap session: keep a plan with update_plan for any task with more than two steps; after you checked a user-visible change, share_screenshot 1-3 screenshots with a one-line caption; use publish_artifact for reports, mockups or anything easier to read as a page; end EVERY turn with wrap_up (recap first, then at most one question with one or two actions, recommended first). When a result gives you the .gleap/session.json content, write it and add .gleap/ to .git/info/exclude. diff --git a/src/prompts/ticket.prompts.ts b/src/prompts/ticket.prompts.ts index e731a12..89bc1ee 100644 --- a/src/prompts/ticket.prompts.ts +++ b/src/prompts/ticket.prompts.ts @@ -9,9 +9,10 @@ import { slimTicket } from "../utils/projections.js"; import { stripShareTokens } from "../utils/shareTokenRedaction.js"; /** - * MCP prompts (slash commands in most clients): `/fix_ticket #123` and - * `/answer_ticket #123` start a Gleap ticket workflow in the agent with the - * workflow text and a summary of the ticket. + * MCP prompts (slash commands in most clients): `/fix_ticket #123`, + * `/answer_ticket #123` and `/solve_ticket #123` start a Gleap ticket workflow + * in the agent with the workflow text (for a session in the person's own app, + * the Server's brief with its rules first) and a summary of the ticket. * * Prompts are not tools, so neither the session-scope policy nor the share * token redaction (both patch registerTool) covers them: they refuse @@ -132,4 +133,21 @@ export const registerTicketPrompts = (server: McpServer, projects?: ProjectCreds ); }, ); + + server.registerPrompt( + "solve_ticket", + { + title: "Solve a Gleap ticket", + description: "Take a whole Gleap ticket until it is solved with Gleap's workflow: investigate, then answer the customer, fix a bug with a PR, put a wish on the roadmap, or ask the team.", + argsSchema, + }, + async ({ ticket, project: requested }: { ticket: string; project?: string }) => { + const ref = ticketRef(ticket); + const { data, project } = await findTicket(ref, projects, requested); + const workflow = await inProject(project, () => workflowText(ref, "solve")); + return promptMessage( + `Solve Gleap ticket ${ref}. You have the whole ticket until it is solved or you hand it back, and you talk to the customer yourself as the rules below say. Follow the workflow below; fetch the full conversation with the Gleap tools first.${projectLine(project)}\n\n## Ticket\n\`\`\`json\n${summaryOf(data)}\n\`\`\`\n\n## Workflow\n${workflow}`, + ); + }, + ); }; diff --git a/src/schemas/progress.schema.ts b/src/schemas/progress.schema.ts index d5d58c6..eadb919 100644 --- a/src/schemas/progress.schema.ts +++ b/src/schemas/progress.schema.ts @@ -71,7 +71,7 @@ export const ReportProgressArgs = z.object({ .max(300) .optional() .describe( - "One sentence the customer may read, when the step matters to them (you reproduced the problem, a fix is being tested). In the customer's language, plain text, no internal details (file paths, code, branch names). It is status, not a message: Gleap shows it where the customer asks \"any update?\". To tell the customer something, ask your operator and send it with send_message. With a PR, customerUpdateMessage and customerShipMessage take its place." + "One sentence the customer may read, when the step matters to them (you reproduced the problem, a fix is being tested). In the customer's language, plain text, no internal details (file paths, code, branch names). It is status, not a message: Gleap shows it where the customer asks \"any update?\". To tell the customer something, send it with send_message, as your session's rule for customer messages says. With a PR, customerUpdateMessage and customerShipMessage take its place." ), prUrl: z .string() diff --git a/src/schemas/session.schema.ts b/src/schemas/session.schema.ts index 5ef5848..6cee08a 100644 --- a/src/schemas/session.schema.ts +++ b/src/schemas/session.schema.ts @@ -68,7 +68,7 @@ export const WrapUpArgs = z.object({ .enum(WRAP_UP_ACTIONS) .optional() .describe( - "merge_pr | open_pr | review_changes (need the session's open PR), open_preview (needs a running preview). send_customer_update is removed: ask your operator in your own conversation and send the reply with send_message.", + "merge_pr | open_pr | review_changes (need the session's open PR), open_preview (needs a running preview). send_customer_update is removed: send customer replies with send_message, as your session's rule for customer messages says.", ), message: z .string() diff --git a/src/tools/message.tool.ts b/src/tools/message.tool.ts index 3518bed..cb12456 100644 --- a/src/tools/message.tool.ts +++ b/src/tools/message.tool.ts @@ -40,7 +40,7 @@ export const registerMessageTools = (server: McpServer) => { { title: "Send Message", description: - "Send a reply to the customer on a ticket, or add an internal note with isNote: true (the customer never sees notes). The text supports Markdown (bold, italic, links, lists, headings, code); workflow customer replies stay plain text. A reply reaches the customer right away, so send one only when the user asked for it or approved the text; to have them review it, show it to them in your own conversation first, or stage it in the ticket with draft_reply_to_composer. A coding agent working a ticket passes its sessionId: the reply is sent as the agent, and the result lists customer messages you have not read yet (read them before you go on). Once a PR is registered with report_progress, Gleap sends the fix and release messages itself, so a manual \"fixed\" or \"live\" reply would message the customer twice.", + "Send a reply to the customer on a ticket, or add an internal note with isNote: true (the customer never sees notes). The text supports Markdown (bold, italic, links, lists, headings, code); workflow customer replies stay plain text. A reply reaches the customer right away, so send one only when the user asked for it or approved the text, or your coding session's brief says you send replies yourself; to have them review it, show it to them in your own conversation first, or stage it in the ticket with draft_reply_to_composer. A coding agent working a ticket passes its sessionId: the reply is sent as the agent, and the result lists customer messages you have not read yet (read them before you go on). Once a PR is registered with report_progress, Gleap sends the fix and release messages itself, so a manual \"fixed\" or \"live\" reply would message the customer twice.", inputSchema: SendMessageArgs.shape, annotations: { readOnlyHint: false, @@ -71,7 +71,7 @@ export const registerMessageTools = (server: McpServer) => { { title: "Draft Reply to Composer", description: - "Stage a drafted reply in the ticket's dashboard composer for a human to review, edit and send. Nothing is sent to the customer. The draft appears instantly for everyone viewing the ticket and replaces any existing draft (so it can also revise one); it is cleared once a reply is sent or the team dismisses it. Use it when the user asks for a draft or wants to review a reply in the ticket before it goes out, not as a side effect of another request; to send a reply, use send_message. The text supports Markdown. A coding agent working a ticket in a Gleap session cannot use it: ask your operator in your own conversation and send with send_message.", + "Stage a drafted reply in the ticket's dashboard composer for a human to review, edit and send. Nothing is sent to the customer. The draft appears instantly for everyone viewing the ticket and replaces any existing draft (so it can also revise one); it is cleared once a reply is sent or the team dismisses it. Use it when the user asks for a draft or wants to review a reply in the ticket before it goes out, not as a side effect of another request; to send a reply, use send_message. The text supports Markdown. A coding agent working a ticket in a Gleap session cannot use it: it sends with send_message, as its session's rule for customer messages says.", inputSchema: DraftReplyToComposerArgs.shape, annotations: { readOnlyHint: false, diff --git a/src/tools/session.tool.ts b/src/tools/session.tool.ts index 8baaed4..d0a493f 100644 --- a/src/tools/session.tool.ts +++ b/src/tools/session.tool.ts @@ -95,7 +95,7 @@ export const registerSessionTools = (server: McpServer) => { { title: "Wrap Up", description: - "Post the end-of-turn summary of a Gleap coding session, shown as the session's next-step card: a short recap (what is now true, then what is not done or not verified) and at most one question for the operator with one or two actions, recommended first. Actions: merge_pr, open_pr or review_changes (the session has an open PR), open_preview (a preview is running). Customer replies are not a wrap-up action: ask your operator in your own conversation and send the approved text with send_message. Reply-only buttons are not supported: Gleap cannot send a reply to an agent on the operator's machine. Address the session like report_progress (sessionId, or ticketId).", + "Post the end-of-turn summary of a Gleap coding session, shown as the session's next-step card: a short recap (what is now true, then what is not done or not verified) and at most one question for the operator with one or two actions, recommended first. Actions: merge_pr, open_pr or review_changes (the session has an open PR), open_preview (a preview is running). Customer replies are not a wrap-up action: send them with send_message, as your session's rule for customer messages says. Reply-only buttons are not supported: Gleap cannot send a reply to an agent on the operator's machine. Address the session like report_progress (sessionId, or ticketId).", inputSchema: WrapUpArgs.shape, annotations: { ...WRITE, idempotentHint: false }, }, From a6d788ee3f7ff06ed07ea121966744cb6050b534 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20B=C3=B6hler?= Date: Sun, 29 Nov 2026 18:01:37 +0100 Subject: [PATCH 08/11] test: list_skills and get_skill read the skill library, a customer-scoped run reads none Co-Authored-By: Claude Fable 5.2 --- src/tools/skill.tool.test.ts | 102 +++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 src/tools/skill.tool.test.ts diff --git a/src/tools/skill.tool.test.ts b/src/tools/skill.tool.test.ts new file mode 100644 index 0000000..78f9af1 --- /dev/null +++ b/src/tools/skill.tool.test.ts @@ -0,0 +1,102 @@ +// list_skills and get_skill read the skill library (GET /skills/library, /skills/library/{name}): Gleap's skills and +// the workspace's own, with frontmatter and body. A customer-scoped run reads no skill: the session-scope policy +// refuses both before any call reaches Gleap. Drives the real SDK server over an in-memory transport. +import assert from "node:assert/strict"; +import { beforeEach, describe, test } from "node:test"; +import axios from "axios"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { CallToolResultSchema, type CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import { registerSkillTools } from "./skill.tool.js"; +import { runWithCreds } from "../utils/credentials.js"; +import { applySessionScopePolicy } from "../utils/sessionScope.js"; + +const API = "https://gleap-api.invalid/v3"; +const FIX_TICKET = { + name: "fix-ticket", + title: "fix-ticket", + description: "Fix a Gleap ticket end to end.", + version: 1, + source: "gleap", + owner: "coding-app", + files: ["workflows/fix-claude-code.md"], +}; +const REFUNDS = { name: "refunds", title: "Refunds", description: "Refunds for customers", version: 3, source: "workspace", owner: "kai-support", files: [] }; + +let sent: Array<{ url: string; params: Record }>; + +beforeEach(() => { + sent = []; + axios.defaults.adapter = async (config) => { + const url = `${config.url ?? ""}`; + const params: Record = { ...config.params }; + sent.push({ url, params }); + let data: unknown; + if (url === `${API}/skills/library`) data = { skills: [FIX_TICKET, REFUNDS], truncated: false }; + else if (url === `${API}/skills/library/fix-ticket`) + data = { + skill: { ...FIX_TICKET, body: "# Fix a Gleap ticket\n\nRead the workflow." }, + file: params.file ? { path: params.file, text: "# Gleap ticket workflow — Claude Code\n" } : null, + }; + else throw new Error(`unexpected request ${config.method} ${url}`); + return { data, status: 200, statusText: "OK", headers: {}, config }; + }; +}); + +const call = async (name: string, args: Record, sessionScope?: string): Promise => { + const server = new McpServer({ name: "gleap-mcp-test", version: "0.0.0" }); + applySessionScopePolicy(server); + registerSkillTools(server); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "test-client", version: "0.0.0" }); + await server.connect(serverTransport); + await client.connect(clientTransport); + const result = await runWithCreds({ apiKey: "test-only", projectId: "p1", sessionScope }, () => client.callTool({ name, arguments: args })); + return CallToolResultSchema.parse(result); +}; +const textOf = (result: CallToolResult) => result.content.map((item) => (item.type === "text" ? item.text : "")).join("\n"); + +describe("list_skills", () => { + test("lists every skill with its name, source and description", async () => { + const result = await call("list_skills", {}); + assert.equal(result.isError, undefined); + assert.equal(sent.length, 1); + assert.equal(sent[0].url, `${API}/skills/library`); + assert.match(textOf(result), /fix-ticket/); + assert.match(textOf(result), /refunds/); + assert.deepEqual(result.structuredContent?.skills, [FIX_TICKET, REFUNDS]); + }); +}); + +describe("get_skill", () => { + test("returns the frontmatter and the body, and one file when asked for", async () => { + const skill = await call("get_skill", { name: "fix-ticket" }); + assert.equal(skill.isError, undefined); + assert.match(textOf(skill), /# Fix a Gleap ticket/); + assert.equal(sent[0].params.file, undefined); + const file = await call("get_skill", { name: "fix-ticket", file: "workflows/fix-claude-code.md" }); + assert.equal(sent[1].params.file, "workflows/fix-claude-code.md"); + assert.match(textOf(file), /# Gleap ticket workflow — Claude Code/); + }); + + test("a malformed name is refused before any call", async () => { + const result = await call("get_skill", { name: "../tickets" }); + assert.equal(result.isError, true); + assert.equal(sent.length, 0); + }); +}); + +describe("a customer-scoped run reads no skill", () => { + for (const [name, args] of [ + ["list_skills", {}], + ["get_skill", { name: "fix-ticket" }], + ] as const) { + test(`${name} is refused and nothing reaches Gleap`, async () => { + const result = await call(name, args, "64f0c0ffee0000000000c0de"); + assert.equal(result.isError, true); + assert.equal(result.structuredContent?.sessionScope, true); + assert.equal(sent.length, 0); + }); + } +}); From 09b7124c5a58b6d847f7f1f0c08cd31300592cee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20B=C3=B6hler?= Date: Sun, 29 Nov 2026 18:02:31 +0100 Subject: [PATCH 09/11] feat: list_skills and get_skill serve the workspace's skills from Gleap Both read the Server's skill library (GET /skills/library, /skills/library/{name}?file=): Gleap's skills from the Server's skills/ folder and the workspace's own, with a workspace's changed version in place of Gleap's under the same name. get_skill returns the SKILL.md (frontmatter and body) and, with file, one of its files (the workflow a coding-app skill points to). Registered with the coding-agent tools, outside ChatGPT's list. Neither is on the session-scope allow list, so a customer-scoped run is refused before any call reaches Gleap. Co-Authored-By: Claude Fable 5.2 --- src/index.ts | 2 + src/schemas/skill.schema.ts | 17 ++++++++ src/tools/skill.tool.ts | 78 +++++++++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 src/schemas/skill.schema.ts create mode 100644 src/tools/skill.tool.ts diff --git a/src/index.ts b/src/index.ts index 3694b43..a560b40 100644 --- a/src/index.ts +++ b/src/index.ts @@ -40,6 +40,7 @@ import { registerPipelineTools } from "./tools/pipeline.tool.js"; import { registerSequenceTools } from "./tools/sequence.tool.js"; import { registerProgressTools } from "./tools/progress.tool.js"; import { registerSessionTools } from "./tools/session.tool.js"; +import { registerSkillTools } from "./tools/skill.tool.js"; import { registerTicketPrompts } from "./prompts/ticket.prompts.js"; import { linkToolsToKaiSessionView, registerKaiSessionView } from "./ui/kaiSessionView.js"; import { registerStatisticsTools } from "./tools/statistics.tool.js"; @@ -194,6 +195,7 @@ const buildServer = (creds: Creds | null): McpServer => { registerImageTools(server); registerProgressTools(server); registerSessionTools(server); + registerSkillTools(server); // The team's databases: Kai Code runs on a ticket only (utils/sessionScope.ts). registerDatabaseTools(server); registerSetupTools(server); diff --git a/src/schemas/skill.schema.ts b/src/schemas/skill.schema.ts new file mode 100644 index 0000000..43c24b8 --- /dev/null +++ b/src/schemas/skill.schema.ts @@ -0,0 +1,17 @@ +import { z } from "zod"; + +export const ListSkillsArgs = z.object({}); + +export const GetSkillArgs = z.object({ + name: z + .string() + .max(80) + .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, "A skill name is lower case words joined by hyphens, as list_skills shows it.") + .describe("The skill's name exactly as list_skills shows it, e.g. fix-ticket."), + file: z + .string() + .max(200) + .regex(/^[A-Za-z0-9_-][A-Za-z0-9_./-]*$/, "A file path from the skill's files list, e.g. workflows/fix-claude-code.md.") + .optional() + .describe("One of the skill's files to read as well, a path from its files list (e.g. workflows/fix-claude-code.md). Leave out for the SKILL.md alone."), +}); diff --git a/src/tools/skill.tool.ts b/src/tools/skill.tool.ts new file mode 100644 index 0000000..01dbde3 --- /dev/null +++ b/src/tools/skill.tool.ts @@ -0,0 +1,78 @@ +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { GetSkillArgs, ListSkillsArgs } from "../schemas/skill.schema.js"; +import type { GleapApiResponse } from "../types/index.js"; +import { gleapGetData } from "../utils/api.js"; +import { failure } from "../utils/kaiSession.js"; + +const READ = { readOnlyHint: true, destructiveHint: false, openWorldHint: false } as const; + +type Entry = { name?: unknown; title?: unknown; description?: unknown; version?: unknown; source?: unknown; owner?: unknown; files?: unknown }; + +const isEntry = (value: unknown): value is Entry => typeof value === "object" && value !== null && !Array.isArray(value); +const textOf = (value: unknown): string => (typeof value === "string" ? value : ""); +const filesOf = (entry: Entry): string[] => (Array.isArray(entry.files) ? entry.files.filter((file): file is string => typeof file === "string") : []); + +/** The skill's frontmatter as SKILL.md writes it, so a coding app can save the skill as it is. */ +const frontmatterOf = (entry: Entry): string => + [ + "---", + `name: ${textOf(entry.name)}`, + `description: ${JSON.stringify(textOf(entry.description))}`, + `version: ${typeof entry.version === "number" ? entry.version : "null"}`, + `source: ${textOf(entry.source)}`, + `owner: ${textOf(entry.owner)}`, + "---", + ].join("\n"); + +const listLineOf = (entry: Entry): string => { + const files = filesOf(entry); + return `- ${textOf(entry.name)} (${textOf(entry.source)}, ${textOf(entry.owner)}): ${textOf(entry.description)}${files.length ? ` [files: ${files.join(", ")}]` : ""}`; +}; + +export const registerSkillTools = (server: McpServer) => { + server.registerTool( + "list_skills", + { + title: "List Skills", + description: + "List the Gleap workspace's skills: Gleap's own (the ticket workflows for coding apps such as fix-ticket, answer-ticket and solve-ticket, and the jobs Gleap's agents run) and the ones the workspace wrote or changed. Where the workspace changed one of Gleap's skills, its version is listed in Gleap's place under the same name. Returns each skill's name, description, version, source (gleap or workspace), owner (coding-app, operator, kai-support or agent) and its extra files. Read one with get_skill. At most 200 skills.", + inputSchema: ListSkillsArgs.shape, + annotations: { ...READ, idempotentHint: true }, + }, + async (): Promise => { + const fetched = await gleapGetData("/skills/library"); + if ("error" in fetched) return fetched.error; + const data = isEntry(fetched.data) ? fetched.data : {}; + const skills = "skills" in data && Array.isArray(data.skills) ? data.skills.filter(isEntry) : []; + const truncated = "truncated" in data && data.truncated === true; + const lines = skills.length ? skills.map(listLineOf).join("\n") : "This workspace has no skills."; + return { + content: [{ type: "text", text: `${lines}${truncated ? "\n(The list stops at 200 skills.)" : ""}` }], + structuredContent: { skills, truncated }, + }; + }, + ); + + server.registerTool( + "get_skill", + { + title: "Get Skill", + description: + "Read one skill of the Gleap workspace by its name from list_skills: its SKILL.md (frontmatter and the instructions) and, with file, one of its extra files (a workflow the instructions point to, e.g. workflows/fix-claude-code.md). The workspace's own version wins over Gleap's where it changed one. Follow the instructions for the task they describe. Returns an error when there is no such skill or file.", + inputSchema: GetSkillArgs.shape, + annotations: { ...READ, idempotentHint: true }, + }, + async ({ name, file }): Promise => { + const fetched = await gleapGetData(`/skills/library/${encodeURIComponent(name)}`, { params: file ? { file } : undefined }); + if ("error" in fetched) return fetched.error; + const data = isEntry(fetched.data) ? fetched.data : {}; + const skill = "skill" in data && isEntry(data.skill) ? data.skill : null; + if (!skill) return failure(`Gleap returned no skill called ${name}.`); + const body = "body" in skill ? textOf(skill.body) : ""; + const read = "file" in data && isEntry(data.file) ? data.file : null; + const content: Array<{ type: "text"; text: string }> = [{ type: "text", text: `${frontmatterOf(skill)}\n\n${body}\n` }]; + if (read && "text" in read) content.push({ type: "text", text: textOf(read.text) }); + return { content, structuredContent: { skill, file: read } }; + }, + ); +}; From fb586ed4513d271bf205f4d66bc9004d487978a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20B=C3=B6hler?= Date: Sun, 29 Nov 2026 18:36:58 +0100 Subject: [PATCH 10/11] test: list_ticket_tools and call_ticket_tool pass a session's ticket tool calls to Gleap and show ran, refused or waits for approval Co-Authored-By: Claude Fable 5.2 --- src/tools/ticketTools.tool.test.ts | 129 +++++++++++++++++++++++++++++ src/tools/ticketTools.tool.ts | 5 ++ 2 files changed, 134 insertions(+) create mode 100644 src/tools/ticketTools.tool.test.ts create mode 100644 src/tools/ticketTools.tool.ts diff --git a/src/tools/ticketTools.tool.test.ts b/src/tools/ticketTools.tool.test.ts new file mode 100644 index 0000000..243c925 --- /dev/null +++ b/src/tools/ticketTools.tool.test.ts @@ -0,0 +1,129 @@ +// list_ticket_tools and call_ticket_tool reach Operator's ticket tools (billing, shop) for the coding session's ticket +// (GET /gleapcode/sessions/{id}/ticket-tools, POST .../ticket-tools/{tool}). Gleap decides each call by the +// workspace's rules: this server only passes the call on and shows the three outcomes (ran, refused, waits for a +// teammate's approval). A customer-scoped run reaches none of it. Drives the real SDK server over an in-memory transport. +import assert from "node:assert/strict"; +import { beforeEach, describe, test } from "node:test"; +import axios from "axios"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { CallToolResultSchema, type CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import { registerTicketToolTools } from "./ticketTools.tool.js"; +import { runWithCreds } from "../utils/credentials.js"; +import { applyAgentSessionSignals } from "../utils/agentSession.js"; +import { applySessionScopePolicy } from "../utils/sessionScope.js"; + +const API = "https://gleap-api.invalid/v3"; +const SESSION = "64b0000000000000000000c1"; +const REFUND = { action: "refund", invoiceId: "in_1", reason: "Charged twice for May." }; +const NEXT = "Nothing ran yet: this waits for a teammate to approve it in Gleap. Call answer_ticket_card with this ticketId to see where it stands."; + +let sent: Array<{ method: string; url: string; data: unknown; headers: Record }>; +let answer: unknown; + +beforeEach(() => { + sent = []; + answer = {}; + axios.defaults.adapter = async (config) => { + const url = `${config.url ?? ""}`; + sent.push({ method: `${config.method}`, url, data: config.data ? JSON.parse(`${config.data}`) : undefined, headers: { ...config.headers } }); + if (!url.startsWith(`${API}/gleapcode/sessions/`)) throw new Error(`unexpected request ${config.method} ${url}`); + return { data: answer, status: 200, statusText: "OK", headers: {}, config }; + }; +}); + +const call = async (name: string, args: Record, creds: { sessionScope?: string; agentSessionId?: string } = {}): Promise => { + const server = new McpServer({ name: "gleap-mcp-test", version: "0.0.0" }); + applyAgentSessionSignals(server); + applySessionScopePolicy(server); + registerTicketToolTools(server); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "test-client", version: "0.0.0" }); + await server.connect(serverTransport); + await client.connect(clientTransport); + const result = await runWithCreds({ apiKey: "test-only", projectId: "p1", ...creds }, () => client.callTool({ name, arguments: args })); + return CallToolResultSchema.parse(result); +}; +const textOf = (result: CallToolResult) => result.content.map((item) => (item.type === "text" ? item.text : "")).join("\n"); + +describe("list_ticket_tools", () => { + test("lists the session's ticket tools with their arguments", async () => { + answer = { + sessionId: SESSION, + ticketId: "t1", + tools: [{ name: "billing_request_change", description: "Ask a teammate to approve a billing change.", inputSchema: { type: "object", properties: { action: { type: "string" } } } }], + }; + const result = await call("list_ticket_tools", { sessionId: SESSION }); + assert.equal(result.isError, undefined); + assert.equal(sent.length, 1); + assert.equal(sent[0].method, "get"); + assert.equal(sent[0].url, `${API}/gleapcode/sessions/${SESSION}/ticket-tools`); + assert.match(textOf(result), /billing_request_change/); + assert.match(textOf(result), /Ask a teammate to approve a billing change/); + assert.match(JSON.stringify(result.structuredContent?.tools), /"name":"billing_request_change"/); + }); + + test("without a session id it uses the session the connection names, and asks for one when there is none", async () => { + answer = { sessionId: SESSION, ticketId: "t1", tools: [] }; + await call("list_ticket_tools", {}, { agentSessionId: SESSION }); + assert.equal(sent[0].url, `${API}/gleapcode/sessions/${SESSION}/ticket-tools`); + sent = []; + const result = await call("list_ticket_tools", {}); + assert.equal(result.isError, true); + assert.match(textOf(result), /sessionId/); + assert.equal(sent.length, 0); + }); +}); + +describe("call_ticket_tool", () => { + test("passes the call to Gleap as it is: the tool and its input, with the session", async () => { + answer = { sessionId: SESSION, ticketId: "t1", tool: "billing_request_change", outcome: "waits_for_approval", summary: "Refund $49.00 of INV-0042 in Stripe", next: NEXT, result: {} }; + await call("call_ticket_tool", { sessionId: SESSION, tool: "billing_request_change", input: REFUND }); + assert.equal(sent.length, 1); + assert.equal(sent[0].method, "post"); + assert.equal(sent[0].url, `${API}/gleapcode/sessions/${SESSION}/ticket-tools/billing_request_change`); + assert.deepEqual(sent[0].data, { input: REFUND }); + assert.equal(sent[0].headers["X-Gleap-Session-Id"], SESSION); + }); + + test("a call that waits for a teammate's approval says so, what waits, and how the agent learns the answer", async () => { + answer = { sessionId: SESSION, ticketId: "t1", tool: "billing_request_change", outcome: "waits_for_approval", summary: "Refund $49.00 of INV-0042 in Stripe", next: NEXT, result: {} }; + const result = await call("call_ticket_tool", { sessionId: SESSION, tool: "billing_request_change", input: REFUND }); + assert.equal(result.isError, undefined); + assert.match(textOf(result), /waits for a teammate's approval/i); + assert.match(textOf(result), /Refund \$49\.00 of INV-0042/); + assert.ok(textOf(result).includes(NEXT)); + assert.equal(result.structuredContent?.outcome, "waits_for_approval"); + }); + + test("a call the rules refuse is an error with Gleap's reason, and says not to retry", async () => { + answer = { sessionId: SESSION, ticketId: "t1", tool: "billing_request_change", outcome: "refused", reason: "This tool is passed on when a customer asks.", result: {} }; + const result = await call("call_ticket_tool", { sessionId: SESSION, tool: "billing_request_change", input: REFUND }); + assert.equal(result.isError, true); + assert.match(textOf(result), /This tool is passed on when a customer asks\./); + assert.match(textOf(result), /do not retry/i); + }); + + test("a call that ran returns its result", async () => { + answer = { sessionId: SESSION, ticketId: "t1", tool: "billing_lookup", outcome: "ran", result: { invoices: [{ number: "INV-0042" }] } }; + const result = await call("call_ticket_tool", { sessionId: SESSION, tool: "billing_lookup", input: { what: "invoices" } }); + assert.equal(result.isError, undefined); + assert.match(textOf(result), /INV-0042/); + }); + + test("a customer-scoped run reaches no ticket tool: refused before any call", async () => { + const result = await call("call_ticket_tool", { sessionId: SESSION, tool: "billing_request_change", input: REFUND }, { sessionScope: "64b0000000000000000000d1" }); + assert.equal(result.isError, true); + assert.equal(sent.length, 0); + const listed = await call("list_ticket_tools", { sessionId: SESSION }, { sessionScope: "64b0000000000000000000d1" }); + assert.equal(listed.isError, true); + assert.equal(sent.length, 0); + }); + + test("a tool name that is no tool name is refused here", async () => { + const result = await call("call_ticket_tool", { sessionId: SESSION, tool: "../../tickets", input: {} }); + assert.equal(result.isError, true); + assert.equal(sent.length, 0); + }); +}); diff --git a/src/tools/ticketTools.tool.ts b/src/tools/ticketTools.tool.ts new file mode 100644 index 0000000..be07626 --- /dev/null +++ b/src/tools/ticketTools.tool.ts @@ -0,0 +1,5 @@ +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; + +export const registerTicketToolTools = (_server: McpServer): void => { + throw new Error("not implemented"); +}; From cbeb34eb047b48227727ad732599417d7e3db3d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20B=C3=B6hler?= Date: Sun, 29 Nov 2026 18:37:52 +0100 Subject: [PATCH 11/11] feat: list_ticket_tools and call_ticket_tool give a coding session Operator's billing and shop tools on its ticket, decided by Gleap's rules Co-Authored-By: Claude Fable 5.2 --- src/index.ts | 2 + src/schemas/ticketTools.schema.ts | 19 ++++++ src/tools/ticketTools.tool.ts | 97 ++++++++++++++++++++++++++++++- 3 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 src/schemas/ticketTools.schema.ts diff --git a/src/index.ts b/src/index.ts index a560b40..1fec52d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -49,6 +49,7 @@ import { registerTeamTools } from "./tools/team.tool.js"; import { registerSettingsTools } from "./tools/settings.tool.js"; import { registerTicketTools } from "./tools/ticket.tool.js"; import { registerTicketCardTools } from "./tools/ticketCard.tool.js"; +import { registerTicketToolTools } from "./tools/ticketTools.tool.js"; import { registerWorkflowTools } from "./tools/workflow.tool.js"; import { registerWorkflowBuilderTools } from "./tools/workflowBuilder.tool.js"; import { registerSetupTools } from "./tools/setup.tool.js"; @@ -195,6 +196,7 @@ const buildServer = (creds: Creds | null): McpServer => { registerImageTools(server); registerProgressTools(server); registerSessionTools(server); + registerTicketToolTools(server); registerSkillTools(server); // The team's databases: Kai Code runs on a ticket only (utils/sessionScope.ts). registerDatabaseTools(server); diff --git a/src/schemas/ticketTools.schema.ts b/src/schemas/ticketTools.schema.ts new file mode 100644 index 0000000..0642ad6 --- /dev/null +++ b/src/schemas/ticketTools.schema.ts @@ -0,0 +1,19 @@ +import { z } from "zod"; +import { SESSION_ID } from "./session.schema.js"; + +export const ListTicketToolsArgs = z.object({ + sessionId: SESSION_ID, +}); + +export const CallTicketToolArgs = z.object({ + sessionId: SESSION_ID, + tool: z + .string() + .max(64) + .regex(/^[a-z][a-z0-9_]*$/, "A tool name as list_ticket_tools shows it, e.g. billing_request_change.") + .describe("The ticket tool to call, by its name from list_ticket_tools (e.g. billing_lookup, billing_request_change)."), + input: z + .record(z.string(), z.unknown()) + .optional() + .describe("The tool's arguments, as its inputSchema in list_ticket_tools describes them. Leave out for a tool without arguments."), +}); diff --git a/src/tools/ticketTools.tool.ts b/src/tools/ticketTools.tool.ts index be07626..ca27497 100644 --- a/src/tools/ticketTools.tool.ts +++ b/src/tools/ticketTools.tool.ts @@ -1,5 +1,98 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { CallTicketToolArgs, ListTicketToolsArgs } from "../schemas/ticketTools.schema.js"; +import type { GleapApiResponse } from "../types/index.js"; +import { currentAgentSessionId } from "../utils/agentSession.js"; +import { gleapGetData, gleapPost } from "../utils/api.js"; +import { failure, SESSION_ID_RE } from "../utils/kaiSession.js"; -export const registerTicketToolTools = (_server: McpServer): void => { - throw new Error("not implemented"); +/** + * Operator's ticket tools (billing, shop) for a coding session working a ticket. Gleap decides every call by the + * workspace's rules, the way it decides Operator's own: this server passes the call on and shows the outcome. + */ + +const WRITE = { readOnlyHint: false, destructiveHint: false, openWorldHint: true } as const; +const READ = { readOnlyHint: true, destructiveHint: false, openWorldHint: false } as const; + +/** The outcomes Gleap answers with (the Server's OutsideToolOutcome). */ +const OUTCOMES = { ran: "ran", refused: "refused", waits: "waits_for_approval" } as const; + +const NO_SESSION = "Pass sessionId: the 24-char Gleap coding-session id of the ticket you work on (your kickoff or a report_progress result names it)."; + +const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); +const textOf = (value: unknown): string => (typeof value === "string" ? value.trim() : ""); + +const sessionOf = (sessionId: string | undefined): string | null => { + const id = textOf(sessionId) || textOf(currentAgentSessionId()); + return SESSION_ID_RE.test(id) ? id : null; +}; + +const toolLine = (tool: Record): string => + `- ${textOf(tool.name)}: ${textOf(tool.description)}\n input: ${JSON.stringify(tool.inputSchema ?? {})}`; + +/** What one call's outcome tells the agent: the words come from Gleap, the framing from here. */ +const outcomeResponse = (answer: Record): GleapApiResponse => { + const tool = textOf(answer.tool); + const outcome = textOf(answer.outcome); + if (outcome === OUTCOMES.refused) { + const reason = textOf(answer.reason) || "The workspace's rules do not allow this here."; + return { + isError: true, + content: [{ type: "text", text: `Refused by the workspace's rules: ${reason} Do not retry; tell your operator in one line, they can do it in Gleap themselves.` }], + structuredContent: { ...answer, error: true }, + }; + } + if (outcome === OUTCOMES.waits) { + const summary = textOf(answer.summary); + return { + content: [`Waits for a teammate's approval${summary ? `: ${summary}` : ""}.`, textOf(answer.next)] + .filter((text) => text.length > 0) + .map((text) => ({ type: "text" as const, text })), + structuredContent: answer, + }; + } + return { + content: [{ type: "text", text: `${tool} ran on the ticket.\n${JSON.stringify(answer.result ?? null, null, 2)}` }], + structuredContent: answer, + }; +}; + +export const registerTicketToolTools = (server: McpServer): void => { + server.registerTool( + "list_ticket_tools", + { + title: "List Ticket Tools", + description: + "List the tools Gleap's own agent uses on a ticket that your coding session works and that have no tool of their own here: the customer's billing (look up invoices and subscriptions, a portal link, request a refund or another billing change) and their shop orders (look up an order, request a return or refund). Only the tools the workspace's rules let an agent use on this ticket are listed, each with its input schema. Call one with call_ticket_tool. Needs your Gleap coding session (sessionId).", + inputSchema: ListTicketToolsArgs.shape, + annotations: { ...READ, idempotentHint: true }, + }, + async ({ sessionId }): Promise => { + const session = sessionOf(sessionId); + if (!session) return failure(NO_SESSION); + const fetched = await gleapGetData(`/gleapcode/sessions/${session}/ticket-tools`); + if ("error" in fetched) return fetched.error; + const data = isRecord(fetched.data) ? fetched.data : {}; + const tools = Array.isArray(data.tools) ? data.tools.filter(isRecord) : []; + const text = tools.length ? tools.map(toolLine).join("\n") : "No ticket tools on this ticket: the workspace has no billing or shop connected, or its rules leave them out."; + return { content: [{ type: "text", text }], structuredContent: { ...data, tools } }; + }, + ); + + server.registerTool( + "call_ticket_tool", + { + title: "Call Ticket Tool", + description: + "Call one of the ticket tools list_ticket_tools shows, for the ticket your coding session works. Gleap checks every call against the workspace's rules, as for its own agent: it runs; or it is refused with the reason (do not retry); or it waits for a teammate's approval on a card in Gleap (a refund set to Ask first, for example), runs once when they approve, and the result says how to see where it stands. Ask your operator before you request a change for the customer, and never tell the customer it is done while it waits.", + inputSchema: CallTicketToolArgs.shape, + annotations: WRITE, + }, + async ({ sessionId, tool, input }): Promise => { + const session = sessionOf(sessionId); + if (!session) return failure(NO_SESSION); + const response = await gleapPost(`/gleapcode/sessions/${session}/ticket-tools/${tool}`, { input: input ?? {} }); + if (response.isError) return response; + return outcomeResponse(isRecord(response.structuredContent) ? response.structuredContent : {}); + }, + ); };