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
86 changes: 51 additions & 35 deletions apps/server/src/issue/IssueService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
isStandaloneIssueTracker,
type IssueTrackerApi,
type StandaloneIssueTrackerApi,
type TrackerIssueDetail,
} from "@t3tools/source-control-core/server/IssueTracker";
import { parseUrl } from "@t3tools/shared/url";

Expand Down Expand Up @@ -164,13 +165,18 @@ export class IssueService extends Context.Service<
) => Effect.Effect<IssueScopeRef & { readonly host: string }, IssueError>;
/**
* Resolve through a matching project, preferring `preferredProjectId`; other scopes are read-only.
* Standalone links must match the workspace in the issue's canonical URL from the connected tracker.
* Standalone links must match the workspace in the issue's canonical URL from the connected
* tracker; that read comes back as `issue`, so callers need not read it again.
*/
readonly resolveUrl: (
url: string,
preferredProjectId?: ProjectId,
) => Effect.Effect<
IssueRef & { readonly host: string; readonly writable: boolean },
IssueRef & {
readonly host: string;
readonly writable: boolean;
readonly issue?: IssueDetail;
},
IssueError
>;
}
Expand Down Expand Up @@ -449,6 +455,20 @@ const make = Effect.gen(function* () {
};
});

const toDetail = (
project: SupportedProject & { readonly writable: boolean },
issue: TrackerIssueDetail,
): IssueDetail => ({
...issue,
tracker: project.tracker,
host: project.host,
scope: project.scope,
projectId: project.project.id,
projectTitle: project.project.title,
writable: project.writable,
capabilities: project.api.capabilities,
});

const detail: IssueService["Service"]["detail"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project) =>
Expand All @@ -461,16 +481,7 @@ const make = Effect.gen(function* () {
})
.pipe(
Effect.mapError(toIssueError("detail")),
Effect.map((issue): IssueDetail => ({
...issue,
tracker: project.tracker,
host: project.host,
scope: project.scope,
projectId: project.project.id,
projectTitle: project.project.title,
writable: project.writable,
capabilities: project.api.capabilities,
})),
Effect.map((issue) => toDetail(project, issue)),
),
),
);
Expand Down Expand Up @@ -692,34 +703,39 @@ const make = Effect.gen(function* () {
if (lender === undefined) {
return yield* new IssueUnavailableError({ reason: "tracker-unsupported" });
}
if (standalone !== null) {
// Team keys repeat across workspaces; only the credential's canonical issue URL identifies one.
const issue = yield* lender.api
.getIssue({
cwd: lender.project.workspaceRoot,
host: lender.host,
scope: link.scope,
key: link.key,
})
.pipe(Effect.mapError(toIssueError("resolveUrl")));
const canonicalUrl = parseUrl(issue.url);
const canonical = canonicalUrl === null ? null : standalone.api.parseIssueUrl(canonicalUrl);
if (canonical === null || canonical.workspace !== standalone.link.workspace) {
return yield* new IssueOperationError({
operation: "resolveUrl",
reason: "not-found",
detail: "This issue URL does not belong to the connected workspace.",
});
}
}
return {
const served = {
...lender,
scope: own === undefined ? link.scope : lender.scope,
writable: own !== undefined,
};
const resolved = {
projectId: lender.project.id,
tracker: lender.tracker,
host: lender.host,
scope: own === undefined ? link.scope : lender.scope,
scope: served.scope,
key: link.key,
writable: own !== undefined,
writable: served.writable,
};
if (standalone === null) return resolved;
// Team keys repeat across workspaces; only the credential's canonical issue URL identifies one.
const issue = yield* lender.api
.getIssue({
cwd: lender.project.workspaceRoot,
host: lender.host,
scope: link.scope,
key: link.key,
})
.pipe(Effect.mapError(toIssueError("resolveUrl")));
const canonicalUrl = parseUrl(issue.url);
const canonical = canonicalUrl === null ? null : standalone.api.parseIssueUrl(canonicalUrl);
if (canonical === null || canonical.workspace !== standalone.link.workspace) {
return yield* new IssueOperationError({
operation: "resolveUrl",
reason: "not-found",
detail: "This issue URL does not belong to the connected workspace.",
});
}
return { ...resolved, issue: toDetail(served, issue) };
},
);

Expand Down
126 changes: 103 additions & 23 deletions apps/server/src/mcp/toolkits/issues/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import {
SourceControlProviderKind,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import {
IssueTrackerError,
type StandaloneIssueTrackerApi,
} from "@t3tools/source-control-core/server/IssueTracker";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
Expand All @@ -18,10 +22,13 @@ import * as Stream from "effect/Stream";
import type { Tool } from "effect/ai";

import * as IssueService from "../../../issue/IssueService.ts";
import * as IssueTrackerRegistry from "../../../issue/IssueTrackerRegistry.ts";
import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
import * as ThreadIssueService from "../../../orchestration-v2/ThreadIssueService.ts";
import { v2PullRequestThread } from "../../../orchestration-v2/testkit/pullRequestFixtures.ts";
import * as IssueTrackerBindings from "../../../persistence/IssueTrackerBindings.ts";
import * as ProjectService from "../../../project/ProjectService.ts";
import * as RepositoryIdentityResolver from "../../../project/RepositoryIdentityResolver.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
Expand Down Expand Up @@ -133,37 +140,41 @@ const detail: IssueDetail = {
linkedPullRequests: [],
};

const projectLayer = Layer.mock(ProjectService.ProjectService)({
getShell: (id) => Effect.succeed(id === PROJECT_ID ? Option.some(project) : Option.none()),
listShells: () => Effect.succeed([project]),
});

const makeHarness = Effect.fn("makeIssuesToolkitHarness")(function* (
issues: ReadonlyArray<ThreadIssueLink> = [],
issueLayer?: Layer.Layer<IssueService.IssueService>,
) {
const links = yield* Ref.make<ReadonlyArray<ThreadIssueService.LinkThreadIssueInput>>([]);
const layerDependencies = Layer.mergeAll(
Layer.mock(ProjectService.ProjectService)({
getShell: (id) => Effect.succeed(id === PROJECT_ID ? Option.some(project) : Option.none()),
listShells: () => Effect.succeed([project]),
}),
projectLayer,
Layer.mock(Orchestrator.OrchestratorV2)({
getThreadShell: (id) => Effect.succeed(id === THREAD_ID ? makeThread(issues) : null),
}),
Layer.mock(IssueService.IssueService)({
detail: () => Effect.succeed(detail),
projectScope: (projectId) =>
Effect.succeed({
projectId,
tracker: GITHUB,
host: "github.com",
scope: "t3tools/t3code",
}),
resolveUrl: (url) =>
Effect.succeed({
projectId: PROJECT_ID,
tracker: GITHUB,
host: "github.com",
scope: "t3tools/t3code",
key: url.split("/").at(-1)!,
writable: true,
}),
}),
issueLayer ??
Layer.mock(IssueService.IssueService)({
detail: () => Effect.succeed(detail),
projectScope: (projectId) =>
Effect.succeed({
projectId,
tracker: GITHUB,
host: "github.com",
scope: "t3tools/t3code",
}),
resolveUrl: (url) =>
Effect.succeed({
projectId: PROJECT_ID,
tracker: GITHUB,
host: "github.com",
scope: "t3tools/t3code",
key: url.split("/").at(-1)!,
writable: true,
}),
}),
Layer.mock(ThreadIssueService.ThreadIssueService)({
link: (input) =>
Ref.update(links, (recorded) => [...recorded, input]).pipe(
Expand Down Expand Up @@ -198,6 +209,75 @@ const makeHarness = Effect.fn("makeIssuesToolkitHarness")(function* (
});

describe("issue toolkit handlers", () => {
it.effect("returns a Linear issue by URL with one issue read left before the rate limit", () =>
Effect.gen(function* () {
const tracker = IssueTrackerKind.make("linear");
const host = "linear.app";
const url = "https://linear.app/acme/issue/ENG-7/seven";
const readsLeft = yield* Ref.make(1);
const linear: StandaloneIssueTrackerApi = {
kind: tracker,
capabilities: detail.capabilities,
standalone: {
tracker,
displayName: "Linear",
host,
scopeNoun: "team",
credential: { label: "Personal API key", helpUrl: null },
},
parseIssueUrl: (link) =>
link.href === url ? { host, workspace: "acme", scope: "ENG", key: "ENG-7" } : null,
probeCredential: () => Effect.succeed({ account: "user", scopes: [] }),
getViewer: () => Effect.succeed("user"),
listIssues: () => Effect.succeed({ items: [], nextCursor: null }),
getComments: () => Effect.succeed({ comments: [], nextCursor: null }),
getIssue: ({ key }) =>
Ref.getAndUpdate(readsLeft, (left) => left - 1).pipe(
Effect.flatMap((left) =>
left > 0
? Effect.succeed({
...detail,
reactions: [],
key,
url,
displayKey: key,
body: "Repro steps",
})
: Effect.fail(
new IssueTrackerError({
tracker,
operation: "getIssue",
reason: "rate-limited",
detail: "Linear's rate limit was reached.",
}),
),
),
),
};
const issueLayer = IssueService.layer.pipe(
Layer.provide(
Layer.mergeAll(
projectLayer,
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({
list: Effect.succeed(new Map([[PROJECT_ID, { tracker, scope: "ENG" }]])),
}),
Layer.succeed(
IssueTrackerRegistry.IssueTrackerRegistry,
IssueTrackerRegistry.fromTrackers([linear]),
),
),
),
);
const harness = yield* makeHarness([], issueLayer);
const result = yield* harness.call("read_issue", { url }).pipe(Effect.result);
expect(result).toMatchObject({
_tag: "Success",
success: { url, displayKey: "ENG-7", title: "Seven", body: "Repro steps" },
});
}),
);

it.effect("refuses a credential without the issues capability", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
Expand Down
10 changes: 8 additions & 2 deletions apps/server/src/mcp/toolkits/issues/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
threadIssueKeysEqual,
type IssueDetail,
type IssueRef,
type OrchestrationV2ThreadShell,
type ProjectId,
Expand Down Expand Up @@ -31,6 +32,8 @@ interface ResolvedTarget extends IssueRef {
readonly host: string;
readonly url: string | null;
readonly writable: boolean;
/** Present when resolving the URL already read the issue. */
readonly issue?: IssueDetail;
}

/** What the tools report from a thread shell; exported so the shape is testable without a layer. */
Expand Down Expand Up @@ -139,6 +142,9 @@ const make = Effect.gen(function* () {
key: target.key,
});

const readIssue = (target: ResolvedTarget) =>
target.issue === undefined ? issues.detail(refOf(target)) : Effect.succeed(target.issue);

/** A link needs the issue's URL, which a key-only reference does not carry; one read fills it. */
const linkFailure = <E>(cause: Cause.Cause<E>) =>
Cause.hasInterruptsOnly(cause)
Expand Down Expand Up @@ -189,7 +195,7 @@ const make = Effect.gen(function* () {
read_issue: McpToolAccess.reads((input) =>
Effect.gen(function* () {
const target = yield* resolveTarget(input);
const detail = yield* issues.detail(refOf(target));
const detail = yield* readIssue(target);
return {
...identityOf(target),
url: target.url ?? detail.url,
Expand Down Expand Up @@ -265,7 +271,7 @@ const make = Effect.gen(function* () {
projectId: input.projectId ?? thread.projectId,
});
// Reading the issue proves it exists and names it for the thread's row.
const detail = yield* issues.detail(refOf(target));
const detail = yield* readIssue(target);
const url = target.url ?? detail.url;
const { alreadyLinked } = yield* threadIssues
.link({
Expand Down
Loading