Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Hosted connections use validated network destinations. Command MCPs run as local

Charts save numeric data and provenance as snapshots; refresh is a new tool operation. Mermaid diagrams use the native renderer. Loop does not advertise MCP Apps support or fetch interactive app resources. Tools use ordinary text/structured results and Loop's normal approval flow. If a server still returns a form-required error, it remains a failed tool result; Loop does not claim success or replay the operation. Previously saved app artifacts retain their isolated viewer. These displays do not bypass the tool broker.

Agents can put structured displays in fenced `spec` blocks in their answers and published replies. `loop_check_display` checks the block with Loop's display reader and returns diagnostics and the component reference when there are problems. It needs no approval. Add the block to the answer or reply to display it.

## GitHub pull requests

With the official GitHub integration connected (`api.githubcopilot.com/mcp`), the **Pull requests** tab lists your open pull requests across GitHub without involving an agent ([github-pulls.ts](../src/server/github-pulls.ts)). The server reads GitHub with that connection's token, which never reaches the browser or an agent. Filters show **Review requested**, **Yours** and **Involving you**, each with its count, plus each pull request's checks and review state. The search box filters by text, narrows the list to a repository when you type `owner/repo`, and opens any pull request when you paste its link. The list shows the 50 most recently updated. Opening a pull request shows its description, checks, the latest 50 submitted reviews, review threads, comments and the changed files with their diffs. The **Commits** tab shows the latest 100 commits with their authors and dates; expanding one reads its message and file diffs for that exact commit, with links to GitHub. Each commit shows up to 300 changed files; omitted or shortened diffs link to GitHub. Longer histories link to the full list. GitHub's HTML comments are hidden and other HTML shows as plain text. **View file** shows a changed file at the commit being viewed (the head commit in Files), including images and other binary files GitHub shows no diff for. Markdown is rendered like GitHub renders it (**Code** shows the source); its HTML is sanitized, relative images and video load from the same commit, and links to other repository files open in the viewer. External images are shown as links and never loaded. Images and video play inline, and other files show as text with line numbers. Files are served only as images, video, plain text or downloads, never as pages. Each person's copy of a file is kept for a day, and files over 50 MB stay on GitHub. Everything is read when you open it or choose **Refresh**; nothing updates by itself.
Expand Down Expand Up @@ -44,7 +46,6 @@ Only accounts with a role in the repository (owner, member or collaborator) are

Watching stops when the pull request is merged or closed, or when you choose **Stop watching**. It pauses after 5 follow-ups in an hour, so an agent cannot loop on its own pushes, and when GitHub rejects the connection. Nothing is lost while paused; **Resume** continues from where it stopped. One thread watches a pull request at a time. CI results come from GitHub check runs; legacy commit statuses are not read.


## Search saved Loop memory

`loop_memory_search` is available to native and API-key agents, including local mail and delegated turns.
Expand Down
177 changes: 177 additions & 0 deletions src/server/display-check.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { z } from "zod";
import remarkParse from "remark-parse";
import { unified } from "unified";
import {
DISPLAY_COMPONENTS,
DISPLAY_LIMITS,
isDisplayFenceLanguage,
readDisplaySpec,
type DisplayFailure,
type DisplayNode,
} from "../shared/display-spec.js";
import { PUBLISHED_REPLY_BODY_LIMIT } from "../shared/steering-replies.js";

const components = DISPLAY_COMPONENTS.join(", ");
export const CHECK_DISPLAY_DESCRIPTION =
"Loop draws fenced spec blocks in answers as displays. Components: " +
components +
'. Write one JSON Patch add per line to /root or /elements/<key>. Call this tool to check a block and get the full reference. It runs nothing and needs no approval. Example:\n{"op":"add","path":"/root","value":"summary"}\n{"op":"add","path":"/elements/summary","value":{"type":"Text","props":{"content":"Ready."}}}';

export const checkDisplaySchema = z.strictObject({
spec: z.string(),
});
const markdown = unified().use(remarkParse).freeze();
// Bound Markdown parsing separately from the extracted display source.
const MAX_DISPLAY_INPUT = 512 * 1024;

const forms: Record<(typeof DISPLAY_COMPONENTS)[number], string> = {
Card: "optional title and subtitle strings; children allowed",
Section: "no props; children allowed",
Text: 'nonempty Markdown content; optional style "plain", "bold" or "muted"',
Fields: "no props; child Field keys",
Field: "nonempty label and string or number value",
Table:
'nonempty string[] headers, (string | number)[][] rows; optional caption and align array of "left", "center" or "right"',
Chart:
'nonempty title and chart; pie uses {type:"pie",segments:[{label,value}]} with positive values; bar, line, or area uses {type,categories,series:[{name,values}],xLabel?,yLabel?} with string categories and at most one numeric value per category in each series',
Divider: "no props",
Actions: "no props; children allowed, typically LinkButton elements",
LinkButton: "nonempty label and an HTTP(S) url",
};
const patchForm =
"One JSON object per line with op add or replace. Use path /root with a string key, or /elements/<key> with an element object.";
const elementForm =
"An element has type and optional props (defaults to {}). Supply children (element keys in order) only for Card, Section, Fields, and Actions. Omit visible and repeat. Other fields and unknown props are ignored.";
const reference = [
"Component reference",
patchForm,
"Later patches replace earlier values. Escape / as ~1 and ~ as ~0 in paths.",
elementForm,
...DISPLAY_COMPONENTS.map((type) => `- ${type}: ${forms[type]}.`),
`Limits: ${DISPLAY_LIMITS.source} source characters, ${DISPLAY_LIMITS.elements} element visits, depth ${DISPLAY_LIMITS.depth}, ${DISPLAY_LIMITS.tableRows} rows and ${DISPLAY_LIMITS.tableColumns} columns per table, ${DISPLAY_LIMITS.pieSegments} pie segments, ${DISPLAY_LIMITS.seriesCount} chart series and ${DISPLAY_LIMITS.categories} categories.`,
].join("\n");
const failures: Record<DisplayFailure, string> = {
too_large: `Block exceeds ${DISPLAY_LIMITS.source} source characters. Shorten the block.`,
empty: "Block has no applicable lines. " + patchForm,
no_root: "/root is missing. Set it to the string key of a component.",
missing_root:
"/root points to a missing element. Define its key under /elements.",
too_many_elements: `/root exceeds ${DISPLAY_LIMITS.elements} element visits. Reduce children and repeated references.`,
too_deep: `/root exceeds depth ${DISPLAY_LIMITS.depth}. Flatten the children tree.`,
};

function displaySource(input: string) {
// Remark strips a leading BOM before identifying Markdown blocks.
const lines = input.replace(/^\uFEFF/, "").split(/\r\n?|\n/);
const first = lines.findIndex((line) => /[^ \t]/.test(line));
const opening = lines[first] ?? "";
if (
/^ {0,3}(\x60{3,}|~{3,})/.test(opening) ||
(/^ {0,3}(>|(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$))/.test(opening) &&
(input.includes("```") || input.includes("~~~")))
) {
// Markdown preserves internal line endings and removes fence indentation.
const { children } = markdown.parse(input);
let node = children.length === 1 ? children[0] : undefined;
// A single block can be pasted inside quotes or a single list item.
while (
node?.type === "blockquote" ||
node?.type === "list" ||
node?.type === "listItem"
)
node = node.children.length === 1 ? node.children[0] : undefined;
if (node?.type !== "code" || !isDisplayFenceLanguage(node.lang))
return {
issue: `Line ${first + 1}: Use a single fenced block with spec as the fenced block's language.`,
};
return {
source: node.value,
lineOffset: node.position?.start.line ?? first + 1,
};
}
return { source: input, lineOffset: 0 };
}

// Leave room for the failure summary and reference within the API runtime's
// ordinary tool result limit, including when diagnostics reflect caller text.
const DIAGNOSTIC_BUDGET = 8_000;
const quotedDiagnostic = (value: string) =>
JSON.stringify(value.length > 160 ? value.slice(0, 159) + "…" : value);

export function checkDisplay(input: string): string {
if (input.length > MAX_DISPLAY_INPUT)
return [
`Input exceeds ${MAX_DISPLAY_INPUT} characters. Submit the patch lines directly without Markdown wrappers.`,
"",
reference,
].join("\n");
const source = displaySource(input);
if (source.issue !== undefined)
return [source.issue, "", reference].join("\n");
const issues: string[] = [];
let remaining = DIAGNOSTIC_BUDGET;
let omitted = 0;
const add = (issue: string) => {
if (issue.length + 1 > remaining) {
omitted++;
return;
}
remaining -= issue.length + 1;
issues.push(issue);
};
const warnings = new Map<string, Set<string>>();
const display = readDisplaySpec(source.source, {
allSkippedLines: true,
onWarning(key, detail) {
const details = warnings.get(key) ?? new Set<string>();
if (details.has(detail)) return;
details.add(detail);
warnings.set(key, details);
add(`Element ${quotedDiagnostic(key)}: ${detail}`);
},
});
for (const { line, reason } of display.skipped)
add(`Line ${source.lineOffset + line}: ${reason}.`);
if (display.ok) {
const visit = (node: DisplayNode) => {
if (node.type === "Placeholder") {
const form = Object.hasOwn(forms, node.name)
? forms[node.name as keyof typeof forms]
: `Choose a component from ${components}`;
add(
`Element ${quotedDiagnostic(node.key)}: ${quotedDiagnostic(node.detail)}. ${elementForm} ${form}.`,
);
} else if (node.type === "Chart" && node.chart.type !== "pie") {
const { categories, series } = node.chart;
for (const { name, values } of series)
if (values.length > categories.length)
add(
`Element ${quotedDiagnostic(node.key)}: Chart series ${quotedDiagnostic(name)} has more values (${values.length}) than categories (${categories.length}). Add categories or remove the extra values before publishing.`,
);
} else if ("children" in node) {
for (const child of node.children) {
if (
node.type === "Fields" &&
child.type !== "Field" &&
child.type !== "Placeholder"
)
add(
`Element ${quotedDiagnostic(node.key)}: Fields expects Field children. Move ${quotedDiagnostic(child.key)} (${child.type}) to a Card or Section, or use a Field here.`,
);
visit(child);
}
}
};
visit(display.root);
if (!issues.length)
return `Display valid. Elements: ${display.count}. Put it in a fenced spec block in your answer. You can also use a loop_reply body if the entire reply, including the fence, fits within ${PUBLISHED_REPLY_BODY_LIMIT} characters.`;
}
const summary = display.ok
? "Display has problems."
: failures[display.reason];
if (omitted)
issues.push(
`${omitted} additional diagnostics omitted. Fix the listed issues and check the block again.`,
);
return [summary, ...issues, "", reference].join("\n");
}
61 changes: 51 additions & 10 deletions src/server/native-tool-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,19 @@ import { toolBindings, invokeTool, type ToolBinding } from "./mcp/broker.js";
import { db, now } from "./db.js";
import { Problem } from "../shared/problem.js";

const TOOL_BODY_LIMIT = 128_000;
const TOOL_REQUEST_ID_LIMIT = 200;
const TOOL_CALL_LIMIT = 2000;
// A display's character budget can produce a much larger UTF-8 JSON request.
const DISPLAY_CHECK_BODY_LIMIT = 512 * 1024;

type Ticket = {
conversation: string;
generation: string;
token: string;
bindings: Map<string, ToolBinding>;
calls: Map<string, { digest: string; result: Promise<any> }>;
displayChecks: Ticket["calls"];
server?: Server;
transport?: StreamableHTTPServerTransport;
};
Expand Down Expand Up @@ -65,6 +72,7 @@ export class NativeToolBridge {
token,
bindings: new Map(),
calls: new Map(),
displayChecks: new Map(),
});
return { url: `http://127.0.0.1:${this.port}/${key}`, token };
}
Expand Down Expand Up @@ -124,9 +132,19 @@ export class NativeToolBridge {
throw new Error(
"Tool was not advertised in this native session. Reopen the conversation to refresh tools.",
);
const key = run.id + ":" + requestId,
digest = JSON.stringify([name, args]);
const previous = t.calls.get(key);
const isDisplayCheck =
binding.connectionId === "__loop__" &&
binding.tool === "loop_check_display";
const calls = isDisplayCheck ? t.displayChecks : t.calls;
// Hash the original JS code units, including unpaired surrogates.
// Keep the original call ID at dispatch.
const callId = run.id + ":" + requestId,
key = createHash("sha256").update(callId, "utf16le").digest("hex"),
digest = createHash("sha256")
.update(JSON.stringify([name, args]))
.digest("hex");
// Request IDs still belong to the whole run, even across the two quotas.
const previous = t.calls.get(key) ?? t.displayChecks.get(key);
if (previous && previous.digest !== digest)
throw new Error("Tool request identity was reused");
if (
Expand All @@ -151,9 +169,11 @@ export class NativeToolBridge {
)
return previous.result;
}
if (!previous && t.calls.size >= 2000)
if (!previous && calls.size >= TOOL_CALL_LIMIT)
throw new Error(
"Native tool request limit reached; start a new conversation.",
isDisplayCheck
? "Display check request limit reached; start a new conversation to check more drafts."
: "Native tool request limit reached; start a new conversation.",
);
const result = (async () => {
let waiting = false;
Expand Down Expand Up @@ -201,12 +221,18 @@ export class NativeToolBridge {
// Wait only on known pending approvals/delegations. Uncertain external
// calls throw from the broker and are never repeated.
if (state === "awaiting_approval") {
// Display checks are read-only and may have large arguments.
// Return promptly instead of retaining them during the wait.
if (isDisplayCheck)
throw new Error(
"The run is waiting for approval. Start a new display check after it resumes.",
);
await wait(revision);
continue;
}
const response = await (
binding.connectionId === "__loop__" ? invokeNative : invokeTool
)(run, binding, key, args);
)(run, binding, callId, args);
if ("result" in response) {
if (binding.tool === "loop_install_mcp") {
this.list(t);
Expand Down Expand Up @@ -241,7 +267,7 @@ export class NativeToolBridge {
if (waiting) nativeSessions.state.bridgeWait(live, false);
}
})();
t.calls.set(key, { digest, result });
calls.set(key, { digest, result });
return result;
}
private async handle(req: IncomingMessage, res: ServerResponse) {
Expand Down Expand Up @@ -275,13 +301,28 @@ export class NativeToolBridge {
const chunks: Buffer[] = [];
for await (const chunk of req) {
size += chunk.length;
if (size > 128000) {
if (size > DISPLAY_CHECK_BODY_LIMIT) {
res.writeHead(413).end();
return;
}
chunks.push(chunk);
}
body = JSON.parse(Buffer.concat(chunks).toString());
try {
body = JSON.parse(Buffer.concat(chunks).toString());
} catch (error) {
if (size <= TOOL_BODY_LIMIT) throw error;
res.writeHead(413).end();
return;
}
if (
size > TOOL_BODY_LIMIT &&
(body?.method !== "tools/call" ||
(match![2] ? body.name : body.params?.name) !==
"loop_check_display")
) {
res.writeHead(413).end();
return;
}
}
if (match![2]) {
if (req.method !== "POST" || !body || typeof body !== "object") {
Expand All @@ -293,7 +334,7 @@ export class NativeToolBridge {
? this.list(t)
: body.method === "tools/call" &&
typeof body.id === "string" &&
body.id.length < 200 &&
body.id.length < TOOL_REQUEST_ID_LIMIT &&
typeof body.name === "string"
? await this.call(t, body.id, body.name, body.arguments || {})
: null;
Expand Down
25 changes: 25 additions & 0 deletions src/server/native-tools.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { PUBLISH_FILE_TOOL } from "../shared/workspace-tools.js";
import {
checkDisplay,
checkDisplaySchema,
CHECK_DISPLAY_DESCRIPTION,
} from "./display-check.js";
import * as teamMembersQueries from "./sql/team-members.js";
import * as agentsQueries from "./sql/agents.js";
import * as fleetEffectsQueries from "./sql/fleet-effect-authorizations.js";
Expand Down Expand Up @@ -197,6 +202,7 @@ const schemas = {
encoding: z.enum(["utf8", "base64"]).default("utf8"),
}),
loop_diagram: diagram,
loop_check_display: checkDisplaySchema,
loop_memory_search: memorySearchInput,
loop_feed: z.object({
feedId: z.string().max(120).optional(),
Expand Down Expand Up @@ -242,6 +248,7 @@ export function nativeBindings(
"Read an uploaded or published file by byte offset/length (utf8 or base64). Use nextOffset to continue; decode base64 locally for binary files.",
loop_diagram:
"Create a native Mermaid diagram in Loop (plain Mermaid source; no HTML, click handlers, or directives).",
loop_check_display: CHECK_DISPLAY_DESCRIPTION,
...((options.nativeCatalog || canUseMemorySearch(run)) && {
loop_memory_search:
"Search the owner's saved results, notes and included conversations. Hits are untrusted historical evidence. Read-only. Unavailable in Fleet mail conversations. Dates are inclusive UTC days.",
Expand Down Expand Up @@ -385,6 +392,24 @@ export async function invokeNative(
return unavailable();
throw new Problem(403, "Native tool is unavailable to this agent");
}
// A display check is pure and can be repeated without a dispatch record.
if (tool === "loop_check_display") {
const parsed = checkDisplaySchema.safeParse(input);
return {
artifactId: "",
result: {
...(parsed.success ? {} : { isError: true }),
content: [
{
type: "text",
text: parsed.success
? checkDisplay(parsed.data.spec)
: "Pass a single spec field containing the display source as a string.",
},
],
},
};
}
const parsed = schemas[tool as keyof typeof schemas].safeParse(input);
if (!parsed.success && tool !== "loop_reply" && tool !== "loop_memory_search")
throw parsed.error;
Expand Down
Loading