Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

Merge commit from fork

Pasqual Tronconeedcc21280f84
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index c7d4dc6b..8cfd5b3d 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -134,6 +134,10 @@ Enforced declaratively through macros, never imperative calls in handlers.
/projects/:projectKey/issues/:sequenceNumber` does the same for an old number that
resolved to an issue now in another project. `POST /issues/:issueId/move` checks the
target project in the `moveTarget` macro, which reads `projectId` from the body.
+ `entityGuard` calls `assertMcpAllowed`, and so does a route that resolves the project
+ itself: it applies the per-project MCP toggle, and refuses an object outside
+ the project an internal agent's run works in (`x-agent-project`, set by the run's tool
+ dispatch).
- Every guard publishes the pair it asserts as `x-permission` on the route's OpenAPI
detail, which is where `mcp/generate.ts` reads it — Elysia deletes a macro's own key
from the route once it expands the macro, so there is nothing else to read it from.
diff --git a/apps/api/src/mcp/dispatch.ts b/apps/api/src/mcp/dispatch.ts
index 83b902ae..a7d3f10d 100644
--- a/apps/api/src/mcp/dispatch.ts
+++ b/apps/api/src/mcp/dispatch.ts
@@ -1,6 +1,6 @@
import type { McpApp } from './types';
import type { McpRouteTool } from './generate';
-import { MCP_LOOPBACK_HEADER, setMcpOAuthToken } from '../shared/mcp-request';
+import { AGENT_PROJECT_HEADER, MCP_LOOPBACK_HEADER, setMcpOAuthToken } from '../shared/mcp-request';
import type { McpCredential } from './credential';
import { structuredResult, type StructuredResult } from './result';
import { withPublicAttachmentUrls, withStoredAttachmentUrls } from './attachment-urls';
@@ -23,12 +23,13 @@ const BASE = 'http://localhost';
// loopback header, and only a request carrying that header is subject to the
// per-project MCP toggle. An internal agent run dispatches through the same routes
// but is not MCP, so disabling MCP on a project must not disarm its agents.
+// projectId is the project an internal agent's run works in (AGENT_PROJECT_HEADER).
export async function dispatchTool(
app: McpApp,
tool: McpRouteTool,
args: Record<string, unknown>,
credential: McpCredential,
- opts: { viaMcpEndpoint: boolean },
+ opts: { viaMcpEndpoint: boolean; projectId?: number },
): Promise<{ text: string; isError: boolean; structuredContent: StructuredResult }> {
const rest = withStoredAttachmentUrls(args);
@@ -59,6 +60,7 @@ export async function dispatchTool(
...(credential.kind === 'api-key' ? { 'x-api-key': credential.apiKey } : {}),
// Marks this as an MCP call so guards enforce the per-project MCP toggle.
...(opts.viaMcpEndpoint ? { [MCP_LOOPBACK_HEADER]: '1' } : {}),
+ ...(opts.projectId != null ? { [AGENT_PROJECT_HEADER]: String(opts.projectId) } : {}),
},
body,
});
diff --git a/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts
index 4c5243fa..86357b3f 100644
--- a/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts
@@ -11,7 +11,7 @@ import { AGENT_ACTIONS, ALWAYS_ON_ACTIONS } from '../../runtime/tools/catalog';
import { routeTools } from '#mcp/generate';
import { getMcpApp } from '#mcp/app-ref';
import { createRole } from '#tests/helpers/roles';
-import { createAgent, setAgentProjectRole } from '#tests/helpers/agents';
+import { createAgent, projectIdOf, setAgentProjectRole } from '#tests/helpers/agents';
// The tools an internal agent runs with, built from the routes tagged mcpTool() and
// dispatched in process with the agent's own API key. What is asserted here is the
@@ -334,3 +334,133 @@ describe('internal agent route tools', () => {
expect(context).toMatchObject({ columns: expect.any(Array) });
});
});
+
+// A run works in one project, and its tools are bound to it: an object addressed by id
+// that belongs to another project of the agent is refused, although the agent's bot
+// is a member there. Without the bound, whoever may start a run in MKT could make the
+// agent read and write OPS.
+describe('internal agent route tools are bound to the run project', () => {
+ beforeEach(async () => {
+ await resetDb();
+ });
+
+ // An agent that works in MKT and OPS, its tools built for a run in MKT, and an issue
+ // of each project.
+ async function crossProject(tools: string[]) {
+ const { asOwner, teamId } = await setup();
+ await createProject(asOwner, { key: 'OPS', name: 'Operations' });
+ const issueIn = async (projectKey: string, title: string) => {
+ const view = await asOwner.projects({ projectKey }).get();
+ const issue = await asOwner
+ .projects({ projectKey })
+ .issues.post({ columnId: view.data!.columns[0]!.id, title });
+ return issue.data!.id;
+ };
+ const mktIssue = await issueIn('MKT', 'Marketing plan');
+ const opsIssue = await issueIn('OPS', 'Pager rota');
+ const created = await createAgent(asOwner, 'MKT', {
+ name: 'Triage Bot',
+ username: `triage-${++agentSeq}`,
+ kind: 'internal',
+ tools,
+ projectIds: [await projectIdOf(asOwner, 'MKT'), await projectIdOf(asOwner, 'OPS')],
+ });
+ const project = await getProjectByRef('MKT', '');
+ if (!project) throw new Error('Test project was not created');
+ const agent = await getAgentById(created.data!.agent.id, teamId);
+ if (!agent) throw new Error('Test agent was not found');
+ const built = buildRouteTools(project, await getInternalAgentApiKey(agent), agent.tools);
+ return { asOwner, tools: built, mktIssue, opsIssue };
+ }
+
+ const outside = { error: { error: 'Outside the project this run works in' } };
+
+ it('refuses reading an issue of another project', async () => {
+ const { tools, mktIssue, opsIssue } = await crossProject([]);
+
+ expect(await run(tools, 'get_issue', { issueId: opsIssue })).toEqual(outside);
+ expect(await run(tools, 'list_issue_activity', { issueId: opsIssue })).toEqual(outside);
+ expect(await run(tools, 'get_issue', { issueId: mktIssue })).toMatchObject({
+ title: 'Marketing plan',
+ });
+ });
+
+ it('refuses writing to an issue of another project', async () => {
+ const { asOwner, tools, mktIssue, opsIssue } = await crossProject([
+ 'add_comment',
+ 'update_issue',
+ ]);
+
+ expect(await run(tools, 'add_comment', { issueId: opsIssue, body: 'From MKT' })).toEqual(
+ outside,
+ );
+ expect(await run(tools, 'update_issue', { issueId: opsIssue, title: 'Renamed' })).toEqual(
+ outside,
+ );
+ expect((await asOwner.issues({ issueId: opsIssue }).get()).data).toMatchObject({
+ title: 'Pager rota',
+ });
+ expect(await run(tools, 'add_comment', { issueId: mktIssue, body: 'Here' })).toMatchObject({
+ body: 'Here',
+ });
+ });
+
+ it('refuses a checklist of an issue of another project', async () => {
+ const { asOwner, tools, opsIssue } = await crossProject(['create_checklist_item']);
+ const checklist = await asOwner
+ .issues({ issueId: opsIssue })
+ .checklists.post({ title: 'Steps' });
+
+ expect(
+ await run(tools, 'create_checklist_item', { checklistId: checklist.data!.id, content: 'x' }),
+ ).toEqual(outside);
+ });
+
+ it('refuses a cycle and an initiative of another project', async () => {
+ const { asOwner, tools } = await crossProject(['update_cycle', 'update_initiative']);
+ const today = new Date().toISOString().slice(0, 10);
+ const cycle = await asOwner
+ .projects({ projectKey: 'OPS' })
+ .cycles.post({ name: 'Sprint 1', startDate: today, endDate: today });
+ const initiative = await asOwner
+ .projects({ projectKey: 'OPS' })
+ .initiatives.post({ title: 'Uptime' });
+
+ expect(await run(tools, 'get_cycle', { cycleId: cycle.data!.id })).toEqual(outside);
+ expect(await run(tools, 'update_cycle', { cycleId: cycle.data!.id, name: 'x' })).toEqual(
+ outside,
+ );
+ expect(await run(tools, 'get_initiative', { initiativeId: initiative.data!.id })).toEqual(
+ outside,
+ );
+ expect(
+ await run(tools, 'update_initiative', { initiativeId: initiative.data!.id, title: 'x' }),
+ ).toEqual(outside);
+ });
+
+ it('refuses any request bound to another project, and ignores a malformed bound', async () => {
+ const { owner, asOwner } = await setup();
+ await createProject(asOwner, { key: 'OPS', name: 'Operations' });
+ const view = await asOwner.projects({ projectKey: 'OPS' }).get();
+ const issue = await asOwner
+ .projects({ projectKey: 'OPS' })
+ .issues.post({ columnId: view.data!.columns[0]!.id, title: 'Pager rota' });
+ const issueId = issue.data!.id;
+ const mkt = String(await projectIdOf(asOwner, 'MKT'));
+ const ops = String(await projectIdOf(asOwner, 'OPS'));
+ const read = (bound: string) =>
+ authedApi(owner.cookie, { 'x-agent-project': bound }).issues({ issueId }).get();
+
+ const refused = await read(mkt);
+ expect(refused.status).toBe(403);
+ expect(refused.error!.value).toMatchObject({ error: 'Outside the project this run works in' });
+ expect((await read(ops)).status).toBe(200);
+ expect((await read('MKT')).status).toBe(200);
+ });
+
+ it('leaves a person reading the same issue alone', async () => {
+ const { asOwner, opsIssue } = await crossProject([]);
+
+ expect((await asOwner.issues({ issueId: opsIssue }).get()).status).toBe(200);
+ });
+});
diff --git a/apps/api/src/modules/agents/core/runtime/tools/route-tools.ts b/apps/api/src/modules/agents/core/runtime/tools/route-tools.ts
index 8b245bc4..bd6a38cb 100644
--- a/apps/api/src/modules/agents/core/runtime/tools/route-tools.ts
+++ b/apps/api/src/modules/agents/core/runtime/tools/route-tools.ts
@@ -21,7 +21,8 @@ import {
// dispatched as an in-process request against the real route with the agent's API
// key, so the route's schema, permission guard, and error model apply unchanged.
// Nothing about an endpoint is restated here: this file only picks which routes an
-// agent gets and binds them to its project.
+// agent gets and binds them to its project: projectKey is filled in, and the guards
+// refuse an object addressed by id that belongs to another project.
//
// An agent's rights are therefore the intersection of two things: the actions it was
// granted (catalog.ts, stored in ai_agent.tools) and what its team role permits.
@@ -118,7 +119,7 @@ function buildOne(
route,
args,
{ kind: 'api-key', apiKey },
- { viaMcpEndpoint: false },
+ { viaMcpEndpoint: false, projectId: project.id },
);
const body = parseBody(text);
// A route failure is returned to the model as a result rather than thrown, so
diff --git a/apps/api/src/shared/guards.ts b/apps/api/src/shared/guards.ts
index fa70982e..b39445dd 100644
--- a/apps/api/src/shared/guards.ts
+++ b/apps/api/src/shared/guards.ts
@@ -23,7 +23,7 @@ import type { ProjectFeature } from './features';
import { getProjectById } from '#modules/projects/service';
import { runsTeam, teamMcpEnabled } from '#modules/teams/service';
import { requireWorkspaceManager } from '#modules/workspaces/service';
-import { isMcpRequest } from './mcp-request';
+import { boundProjectId, isMcpRequest } from './mcp-request';
import { HttpError } from './lib';
import type { PermissionResource, PermissionAction } from './permissions';
@@ -92,10 +92,15 @@ export function entityGuard(
});
}
-// The per-project MCP toggle, for a route or a guard that resolved the project by
-// its id rather than through one of the :projectKey macros. A plain request passes
-// untouched.
+// What the request carries about the project, for a route or a guard that resolved the
+// project by an object's id rather than through one of the :projectKey macros: an
+// internal agent's run is bound to its own project, and an MCP call obeys the
+// per-project MCP toggle. A plain request passes untouched.
export async function assertMcpAllowed(projectId: number, headers: Headers): Promise<void> {
+ const bound = boundProjectId(headers);
+ if (bound != null && bound !== projectId) {
+ throw new HttpError(403, 'Outside the project this run works in');
+ }
if (!isMcpRequest(headers)) return;
const project = await getProjectById(projectId);
if (project) assertMcpEnabled(project, true);
diff --git a/apps/api/src/shared/mcp-request.ts b/apps/api/src/shared/mcp-request.ts
index 7c352a48..14c09e0a 100644
--- a/apps/api/src/shared/mcp-request.ts
+++ b/apps/api/src/shared/mcp-request.ts
@@ -7,6 +7,11 @@
// restriction, never remove it, so it is safe to trust.
export const MCP_LOOPBACK_HEADER = 'x-mcp-loopback';
+// The project an internal agent's run works in, set on each tool call it dispatches.
+// A route that resolves a project by an object's id refuses any other project. Like
+// the loopback header, a forged value can only narrow what the caller reaches.
+export const AGENT_PROJECT_HEADER = 'x-agent-project';
+
const oauthTokens = new WeakMap<Request, string>();
// True when the request came from an MCP tool dispatch.
@@ -14,6 +19,12 @@ export function isMcpRequest(headers: Headers): boolean {
return headers.get(MCP_LOOPBACK_HEADER) === '1';
}
+// The project the request is bound to, or null when it carries none.
+export function boundProjectId(headers: Headers): number | null {
+ const value = Number(headers.get(AGENT_PROJECT_HEADER));
+ return Number.isInteger(value) && value > 0 ? value : null;
+}
+
export function setMcpOAuthToken(request: Request, token: string): void {
oauthTokens.set(request, token);
}