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
11 changes: 11 additions & 0 deletions apps/server/src/issues/IssueEligibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
type ProviderDriverKind,
type ThreadLinkedIssue,
} from "@t3tools/contracts";
import type { ManagedIssueRole } from "@t3tools/provider-core/server/mcpSession";

export const isReadOnlyIssueRole = (role: string | undefined) => {
const resolved = role === undefined ? undefined : resolveThreadRole(role);
Expand Down Expand Up @@ -36,6 +37,16 @@ export const requiresManagedIssueAdmission = (
parent.linkedIssue !== undefined ||
root.repositoryOrchestration !== undefined);

/** Linked issue workers and the repository root get managed orchestration instructions. */
export const managedIssueRole = (
thread: Pick<OrchestrationV2AppThread, "linkedIssue" | "repositoryOrchestration">,
): ManagedIssueRole | undefined =>
thread.linkedIssue !== undefined
? "worker"
: thread.repositoryOrchestration !== undefined
? "root"
: undefined;

/** Codex and Claude drivers; IssueEligibility.test.ts ties these names to the real drivers. */
export const supportsManagedIssueWork = (driver: ProviderDriverKind) =>
driver === "codex" || driver === "claudeAgent";
Expand Down
10 changes: 5 additions & 5 deletions apps/server/src/mcp/ManagedIssueDelegation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import {
requiresManagedIssueAdmission,
} from "../issues/IssueEligibility.ts";

export const makeManagedIssueDelegation = Effect.gen(function* () {
export const makeManagedIssueDelegation = Effect.fn("ManagedIssueDelegation.make")(function* (
loadThread: (id: ThreadId) => Effect.Effect<OrchestrationV2AppThread, OrchestratorMcpFailure>,
) {
const issueWork = yield* Effect.serviceOption(IssueWorkService.IssueWorkService);
const issueLinks = yield* Effect.serviceOption(IssueLinks.IssueLinks);
const issueService = yield* Effect.serviceOption(IssueService.IssueService);
Expand All @@ -29,13 +31,12 @@ export const makeManagedIssueDelegation = Effect.gen(function* () {
const resolveIssue = Effect.fnUntraced(function* (
input: OrchestratorMcpDelegateTaskInput,
parent: { readonly thread: OrchestrationV2AppThread },
loadRoot: (id: ThreadId) => Effect.Effect<OrchestrationV2AppThread, OrchestratorMcpFailure>,
) {
const unmanaged = isUnmanagedIssueRole(input.role);
const root =
unmanaged || parent.thread.lineage.rootThreadId === parent.thread.id
? parent.thread
: yield* loadRoot(parent.thread.lineage.rootThreadId);
: yield* loadThread(parent.thread.lineage.rootThreadId);
const managed = requiresManagedIssueAdmission(input.role, parent.thread, root);
if (unmanaged && input.issue !== undefined && Option.isNone(issueLinks))
return yield* failure("orchestration_error", "Issue linking is unavailable on this server.");
Expand Down Expand Up @@ -118,12 +119,11 @@ export const makeManagedIssueDelegation = Effect.gen(function* () {
taskResult: OrchestratorMcpDelegateTaskResult,
parent: OrchestrationV2AppThread,
taskCommand: Extract<OrchestrationV2ServerCommand, { type: "delegated_task.request" }>,
loadRoot: (id: ThreadId) => Effect.Effect<OrchestrationV2AppThread, OrchestratorMcpFailure>,
) {
if (taskResult.status !== "queued" || Option.isNone(issueWork)) return taskResult;
const root =
parent.repositoryOrchestration === undefined
? yield* loadRoot(parent.lineage.rootThreadId)
? yield* loadThread(parent.lineage.rootThreadId)
: parent;
const config = root?.repositoryOrchestration;
if (config === undefined) return taskResult;
Expand Down
73 changes: 73 additions & 0 deletions apps/server/src/mcp/OrchestratorMcpService.fork.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
CommandId,
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
IssueWorkError,
NodeId,
OrchestratorMcpTarget,
ProjectId,
Expand All @@ -34,6 +35,7 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";

import * as IssueChangeService from "../issues/IssueChangeService.ts";
import * as IssueWorkService from "../issues/IssueWorkService.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
Expand Down Expand Up @@ -1718,4 +1720,75 @@ describe("OrchestratorMcpService provider resolution", () => {
assert.equal(restored.code, "runtime_mode_escalation_denied");
}),
);

it.effect("refuses issue proposals from an outside client and a retired root's subtree", () =>
Effect.gen(function* () {
const retiredThreadId = ThreadId.make("thread:retired-worker");
const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe(
Effect.provide(
layerOrchestratorService.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mergeAll(NodeServices.layer, NodeCrypto.layer),
Layer.mock(ThreadManagementService.ThreadManagementService)({}),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
Layer.mock(ProjectService.ProjectService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
Layer.mock(IssueWorkService.IssueWorkService)({
assertCurrentCaller: (threadId) =>
threadId === retiredThreadId
? Effect.fail(
new IssueWorkError({ code: "retired-root", message: "Root retired." }),
)
: Effect.void,
}),
Layer.mock(IssueChangeService.IssueChangeService)({
propose: () => Effect.die("A refused caller reached the issue proposal."),
}),
),
),
),
),
);
const input = {
host: "github.com",
repository: "acme/app",
clientRequestId: "proposal",
operation: { type: "state", number: 13, state: "closed" },
} as const;
const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment:proposal"),
requestNamespace: "client:proposal",
thread: undefined,
client: { sessionId: "proposal", label: "Claude Code", access: "full-access" },
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
const outside = yield* mcp.proposeIssueChange(scope, input).pipe(Effect.flip);
const retired = yield* mcp
.proposeIssueChange(
{
...scope,
client: undefined,
thread: {
threadId: retiredThreadId,
providerSessionId: "retired-session",
providerInstanceId: codexInstanceId,
},
},
input,
)
.pipe(Effect.flip);
assert.deepEqual(
[outside.code, outside.message],
["invalid_request", "Issue proposals require a managed thread."],
);
assert.deepEqual([retired.code, retired.message], ["invalid_request", "Root retired."]);
}),
);
});
66 changes: 13 additions & 53 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,6 @@ type TerminalTaskStatus = Extract<
>;

export interface OrchestratorMcpServiceShape extends RepositoryMcpMethods {
readonly proposeIssueChange: (
scope: McpInvocationScope,
input: import("@t3tools/contracts").IssueChangeProposeInput,
) => Effect.Effect<import("@t3tools/contracts").IssueChange, OrchestratorMcpFailure>;
readonly capabilities: (
scope: McpInvocationScope,
input?: OrchestratorMcpCapabilitiesInput,
Expand Down Expand Up @@ -1266,7 +1262,12 @@ const make = Effect.gen(function* () {
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
const gitDriver = yield* GitVcsDriver.GitVcsDriver;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const managedIssueDelegation = yield* makeManagedIssueDelegation;
const loadThreadRow = (threadId: ThreadId) =>
threadManagement.getThreadRecords(threadId, []).pipe(
Effect.map((records) => records.thread),
Effect.mapError(threadManagementFailure),
);
const managedIssueDelegation = yield* makeManagedIssueDelegation(loadThreadRow);
const issueWork = yield* Effect.serviceOption(IssueWorkService.IssueWorkService);
const issueChanges = yield* Effect.serviceOption(IssueChangeService.IssueChangeService);
const remoteDelegation = yield* Effect.serviceOption(RemoteDelegation.RemoteDelegation);
Expand Down Expand Up @@ -1518,12 +1519,7 @@ const make = Effect.gen(function* () {

const loadProviders = providerRegistry.getProviders;
const loadUsageSprint = (thread: OrchestrationV2ThreadProjection["thread"]) =>
lineageUsageSprint(thread, (threadId) =>
threadManagement.getThreadRecords(threadId, []).pipe(
Effect.map((records) => records.thread),
Effect.mapError(threadManagementFailure),
),
);
lineageUsageSprint(thread, loadThreadRow);

const loadOrchestrationCapableInstanceIds = () =>
providerAdapters.list().pipe(Effect.map((instanceIds) => new Set(instanceIds)));
Expand Down Expand Up @@ -2286,27 +2282,14 @@ const make = Effect.gen(function* () {

const repositoryMcp = makeRepositoryMcpMethods({
issueWork,
issueChanges,
requireCapability,
loadCaller: (scope) => loadCaller(scope, ["runs"]),
loadThreadCaller,
});
const { assertCurrentRepositoryCaller } = repositoryMcp;

return OrchestratorMcpService.of({
proposeIssueChange: Effect.fn("OrchestratorMcpService.proposeIssueChange")(
function* (scope, input) {
yield* requireCapability(scope);
if (scope.thread === undefined || Option.isNone(issueChanges))
return yield* failure("invalid_request", "Issue proposals require a managed thread.");
// A retired root's subtree may finish its work but not plan new issue changes.
if (Option.isSome(issueWork))
yield* issueWork.value
.assertCurrentCaller(scope.thread.threadId)
.pipe(Effect.mapError((error) => failure("invalid_request", error.message)));
return yield* issueChanges.value
.propose(scope.thread.threadId, input)
.pipe(Effect.mapError((error) => failure("invalid_request", error.message)));
},
),
...repositoryMcp.methods,
scheduleTask: Effect.fn("OrchestratorMcpService.scheduleTask")(function* (scope, input) {
yield* assertCurrentRepositoryCaller(scope);
Expand Down Expand Up @@ -2759,10 +2742,7 @@ const make = Effect.gen(function* () {
if (input.target !== undefined && environmentId !== undefined) {
yield* requireCapability(callerScope);
const scope = yield* requireThreadScope(callerScope, "delegate_task");
const caller = yield* threadManagement.getThreadRecords(scope.thread.threadId, []).pipe(
Effect.map((records) => records.thread),
Effect.mapError(threadManagementFailure),
);
const caller = yield* loadThreadRow(scope.thread.threadId);
// The sprint cannot stop a child that runs on another environment.
const sprint = yield* loadUsageSprint(caller);
if (sprint !== undefined)
Expand All @@ -2782,10 +2762,7 @@ const make = Effect.gen(function* () {
: readTask(scope, taskId, false, true);
}
const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task");
if (Option.isSome(issueWork))
yield* issueWork.value
.assertCurrentCaller(parent.thread.id)
.pipe(Effect.mapError((error) => failure("invalid_request", error.message)));
yield* assertCurrentRepositoryCaller(scope);
if (
input.target?.projectId !== undefined &&
input.target.projectId !== parent.thread.projectId
Expand All @@ -2808,15 +2785,7 @@ const make = Effect.gen(function* () {
"Delegated tasks require an active run owned by this MCP provider session.",
);
}
const { unmanaged, linkedIssue } = yield* managedIssueDelegation.resolveIssue(
input,
parent,
(id) =>
threadManagement.getThreadRecords(id, []).pipe(
Effect.map((records) => records.thread),
Effect.mapError(threadManagementFailure),
),
);
const { unmanaged, linkedIssue } = yield* managedIssueDelegation.resolveIssue(input, parent);
const providers = yield* loadProviders;
const key = yield* requestKey(input.clientRequestId);
const commandId = stableCommandId({
Expand Down Expand Up @@ -2971,16 +2940,7 @@ const make = Effect.gen(function* () {
? awaitTask(scope, taskId, key, input.timeoutMs)
: readTask(scope, taskId, false, true),
);
return yield* managedIssueDelegation.withQueueNote(
taskResult,
parent.thread,
taskCommand,
(id) =>
threadManagement.getThreadRecords(id, []).pipe(
Effect.map((records) => records.thread),
Effect.mapError(threadManagementFailure),
),
);
return yield* managedIssueDelegation.withQueueNote(taskResult, parent.thread, taskCommand);
}),
taskStatus: Effect.fn("OrchestratorMcpService.taskStatus")(function* (callerScope, taskId) {
const scope = yield* requireThreadScope(callerScope, "task_status");
Expand Down
23 changes: 23 additions & 0 deletions apps/server/src/mcp/RepositoryOrchestrationMcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@ import {
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type * as IssueChangeService from "../issues/IssueChangeService.ts";
import type * as IssueWorkService from "../issues/IssueWorkService.ts";
import type { McpInvocationScope, McpThreadInvocationScope } from "./McpInvocationContext.ts";
import { resolveRuntimeMode, resolveInteractionMode } from "./delegatedTaskModes.ts";
export interface RepositoryMcpMethods {
readonly proposeIssueChange: (
scope: McpInvocationScope,
input: import("@t3tools/contracts").IssueChangeProposeInput,
) => Effect.Effect<import("@t3tools/contracts").IssueChange, OrchestratorMcpFailure>;
readonly requestRepositoryHandoff: (
scope: McpInvocationScope,
input: import("@t3tools/contracts").RepositoryHandoffRequestInput,
Expand Down Expand Up @@ -62,6 +67,10 @@ export interface RepositoryMcpMethods {

interface RepositoryMcpHooks {
readonly issueWork: Option.Option<IssueWorkService.IssueWorkService["Service"]>;
readonly issueChanges: Option.Option<IssueChangeService.IssueChangeService["Service"]>;
readonly requireCapability: (
scope: McpInvocationScope,
) => Effect.Effect<void, OrchestratorMcpFailure>;
readonly loadCaller: (scope: McpInvocationScope) => Effect.Effect<
{
readonly limits: {
Expand All @@ -85,6 +94,8 @@ interface RepositoryMcpHooks {

export function makeRepositoryMcpMethods({
issueWork,
issueChanges,
requireCapability,
loadCaller,
loadThreadCaller,
}: RepositoryMcpHooks) {
Expand All @@ -109,6 +120,18 @@ export function makeRepositoryMcpMethods({
});

const methods: RepositoryMcpMethods = {
proposeIssueChange: Effect.fn("OrchestratorMcpService.proposeIssueChange")(
function* (scope, input) {
yield* requireCapability(scope);
if (scope.thread === undefined || Option.isNone(issueChanges))
return yield* failure("invalid_request", "Issue proposals require a managed thread.");
// A retired root's subtree may finish its work but not plan new issue changes.
yield* assertCurrentRepositoryCaller(scope);
return yield* issueChanges.value
.propose(scope.thread.threadId, input)
.pipe(Effect.mapError((error) => failure("invalid_request", error.message)));
},
),
requestRepositoryHandoff: Effect.fn("OrchestratorMcpService.requestRepositoryHandoff")(
function* (scope, input) {
const caller = yield* loadThreadCaller(scope, "request_repository_handoff");
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ const threadMetadataDependencies = [
];
const ProposeIssueChangeTool = Tool.make("propose_issue_change", {
description:
"Propose an exact issue change from a repository-managed thread. Create needs title, body and milestoneNumber (null for none); split needs number and issues with those fields. Other operations need number and their action, state, body, milestoneNumber, childNumber or blockerNumber. Use a stable clientRequestId on retries. Create/split and milestone moves execute automatically. Body edits, close/reopen, standalone parent changes, and blocked_by add/remove also execute automatically, unless the requesting thread is in approval-required mode; then they wait for the user's approval on the Issues page. The returned change includes the exact preview, decision and result. Agents cannot approve changes. A conflict needs a new proposal and preview. Labels and assignees are outside this tool's scope.",
"Propose an exact issue change from a repository-managed thread. Create needs title, body and milestoneNumber (null for none); split needs number and issues with those fields. Other operations need number and their action, state, body, milestoneNumber, childNumber or blockerNumber. Use a stable clientRequestId on retries. Create/split and milestone moves execute automatically. Body edits, close/reopen, standalone parent changes, and blocked_by add/remove also execute automatically, unless the requesting thread is in approval-required mode; then they wait for the user's approval in the issue panel. The returned change includes the exact preview, decision and result. Agents cannot approve changes. A conflict needs a new proposal and preview. Labels and assignees are outside this tool's scope.",
parameters: IssueChangeProposeInput,
success: IssueChange,
failure: OrchestratorMcpFailure,
Expand Down
Loading