Skip to content
Open
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
7 changes: 7 additions & 0 deletions apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ import {
import * as WorktreeHandlers from "./toolkits/worktree/handlers.ts";
import { WorktreeToolkit } from "./toolkits/worktree/tools.ts";
import * as WorktreeMcpService from "./WorktreeMcpService.ts";
import * as EventsHandlers from "./toolkits/events/handlers.ts";
import { EventsToolkit } from "./toolkits/events/tools.ts";
import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts";
import * as ToolSearchHandlers from "./toolkits/toolSearch/handlers.ts";
import { ToolSearchToolkit } from "./toolkits/toolSearch/tools.ts";
Expand Down Expand Up @@ -1315,6 +1317,10 @@ export const layerPullRequestsToolkit = toolkitRegistration(
PullRequestsHandlers.layer,
).pipe(Layer.provide(PullRequestWatchService.layer));

export const layerEventsToolkit = toolkitRegistration(EventsToolkit, EventsHandlers.layer).pipe(
Layer.provide(PullRequestWatchService.layer),
);

const layerDeviceStandardToolkitRegistration = toolkitRegistration(
DeviceStandardToolkit,
DeviceHandlers.layerStandard,
Expand Down Expand Up @@ -1372,6 +1378,7 @@ export const layerTools = Layer.mergeAll(
layerPreviewControlsRegistration,
layerWorktreeToolkitRegistration,
layerPullRequestsToolkit,
layerEventsToolkit,
layerDeviceToolkit,
layerHtmlToolkit,
layerMessageToolkit,
Expand Down
15 changes: 15 additions & 0 deletions apps/server/src/mcp/advertisedJsonSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,22 @@ const mergeTaggedObjects = (branches: ReadonlyArray<Json>): JsonObject | undefin
return { type: "object", properties, required: [tag, ...requiredByAll] };
};

// Effect encodes `Schema.Struct({})` as "not null". MCP requires `type: object`.
const isEmptyObjectSchema = (value: Json) =>
Predicate.isObject(value) &&
isNullSchema(value.not) &&
(value.allOf === undefined ||
(Array.isArray(value.allOf) &&
value.allOf.every(
(part) =>
Predicate.isObject(part) &&
part.type === "object" &&
Predicate.isObject(part.properties) &&
Object.keys(part.properties).length === 0,
)));

const compact = (schema: Json, optional: boolean): Json => {
if (isEmptyObjectSchema(schema)) return { type: "object", properties: {} };
if (Array.isArray(schema)) return schema.map((item) => compact(item, false));
if (!Predicate.isObject(schema)) return schema;
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
Expand Down
124 changes: 124 additions & 0 deletions apps/server/src/mcp/toolkits/events/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import {
EventSubscriptionInvalidError,
PullRequestUnavailableError,
ThreadId,
} from "@t3tools/contracts";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";

import { prepareSubscribe } from "../../../orchestration-v2/eventSubscription.ts";
import * as EventSubscriptionStore from "../../../persistence/EventSubscriptions.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import {
PullRequestHostRequiredError,
PullRequestTargetIncompleteError,
PullRequestUrlInvalidError,
PullRequestUrlUnavailableError,
} from "../../../pullRequest/pullRequestTarget.ts";
import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
import { EventsToolkit, type EventSubscribeInput } from "./tools.ts";

const unavailable = () =>
new EventSubscriptionInvalidError({
detail: "Event subscriptions are not available on this server.",
});

type WatchPullRequestError =
| PullRequestWatchService.PullRequestWatchFailedError
| PullRequestWatchService.PullRequestNotOpenError
| PullRequestWatchService.PullRequestWatchFromSubagentError
| PullRequestWatchService.PullRequestWatchThreadNotFoundError
| PullRequestUrlInvalidError
| PullRequestTargetIncompleteError
| PullRequestHostRequiredError
| PullRequestUrlUnavailableError
| PullRequestUnavailableError;

export const subscribeEvent = Effect.fn("EventsToolkit.subscribe")(function* (input: {
readonly callerThreadId: ThreadId;
readonly request: EventSubscribeInput;
readonly store: EventSubscriptionStore.EventSubscriptionStore["Service"] | null;
readonly watchPullRequest: (url: string) => Effect.Effect<void, WatchPullRequestError>;
readonly id: string;
readonly createdAt: string;
}) {
const prepared = prepareSubscribe({
id: input.id,
subscriberThreadId: input.callerThreadId,
selector: input.request.selector,
events: input.request.events,
ignoreAuthors: input.request.ignoreAuthors,
delivery: input.request.delivery,
createdAt: input.createdAt,
});
if (!prepared.ok) return yield* prepared.error;
if (input.store === null) return yield* unavailable();
const selector = prepared.subscription.selector;
if (selector.entity === "pull_request" && selector.by === "url") {
yield* input.watchPullRequest(selector.url);
}
return yield* input.store.put(prepared.subscription);
});

export const layer = McpToolAccess.toLayer(
EventsToolkit,
Effect.gen(function* () {
const subscriptions = yield* Effect.serviceOption(
EventSubscriptionStore.EventSubscriptionStore,
);
const watches = yield* PullRequestWatchService.PullRequestWatchService;
const random = yield* SecureRandom.SecureRandom;
const store = Option.getOrNull(subscriptions);

const callerThreadId = Effect.gen(function* () {
const scope = yield* McpInvocationContext.McpInvocationContext;
const threadId = scope.thread?.threadId;
if (threadId === undefined) {
return yield* new EventSubscriptionInvalidError({
detail: "This tool must be called from a thread.",
});
}
return threadId;
});

return {
t3_event_subscribe: McpToolAccess.actsAsCaller((request) =>
Effect.gen(function* () {
const callerThreadId_ = yield* callerThreadId;
const id = `evt_${yield* random.uuidV4().pipe(Effect.orDie)}`;
const createdAt = DateTime.formatIso(yield* DateTime.now);
return yield* subscribeEvent({
callerThreadId: callerThreadId_,
request,
store,
id,
createdAt,
watchPullRequest: (url) =>
watches
.setWatching({
threadId: callerThreadId_,
target: { url },
watching: true,
})
.pipe(Effect.asVoid),
});
}),
),
t3_event_unsubscribe: McpToolAccess.actsAsCaller(({ id }) =>
Effect.gen(function* () {
if (store === null) return yield* unavailable();
return yield* store.remove(yield* callerThreadId, id);
}),
),
t3_event_list: McpToolAccess.readsAsCaller(() =>
Effect.gen(function* () {
if (store === null) return yield* unavailable();
return { subscriptions: yield* store.listForSubscriber(yield* callerThreadId) };
}),
),
};
}),
);
118 changes: 118 additions & 0 deletions apps/server/src/mcp/toolkits/events/tools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import {
EventFilter,
EventSelector,
EventSubscription,
EventSubscriptionInvalidError,
EventSubscriptionPhase2Error,
EventSubscriptionSelectorUnsupportedError,
OrchestratorMcpFailure,
QuietHours,
} from "@t3tools/contracts";
import { McpSchema, Tool, Toolkit } from "effect/ai";
import * as Schema from "effect/Schema";

import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
import { PersistenceDecodeError, PersistenceSqlError } from "../../../persistence/Errors.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
import {
PullRequestHostRequiredError,
PullRequestTargetIncompleteError,
PullRequestUrlInvalidError,
PullRequestUrlUnavailableError,
} from "../../../pullRequest/pullRequestTarget.ts";
import { PullRequestUnavailableError } from "@t3tools/contracts";

const dependencies = [
McpInvocationContext.McpInvocationContext,
ThreadManagementService.ThreadManagementService,
PullRequestWatchService.PullRequestWatchService,
];

const DeliveryInput = Schema.Struct({
immediate: Schema.optional(Schema.Boolean),
coalesceWindowSeconds: Schema.optional(Schema.Int),
autoExpireOnClose: Schema.optional(Schema.Boolean),
onlyWhenIdle: Schema.optional(Schema.Boolean),
quietHours: Schema.optional(QuietHours),
maxWakesPerHour: Schema.optional(Schema.Int),
});

export const EventSubscribeInput = Schema.Struct({
selector: EventSelector,
events: Schema.Array(EventFilter),
ignoreAuthors: Schema.optional(Schema.Array(Schema.String)),
delivery: Schema.optional(DeliveryInput),
});
export type EventSubscribeInput = typeof EventSubscribeInput.Type;

export const EventUnsubscribeInput = Schema.Struct({
id: Schema.String,
});
export type EventUnsubscribeInput = typeof EventUnsubscribeInput.Type;

const failure = Schema.Union([
OrchestratorMcpFailure,
EventSubscriptionPhase2Error,
EventSubscriptionSelectorUnsupportedError,
EventSubscriptionInvalidError,
PersistenceSqlError,
PersistenceDecodeError,
PullRequestWatchService.PullRequestWatchFailedError,
PullRequestWatchService.PullRequestNotOpenError,
PullRequestWatchService.PullRequestWatchFromSubagentError,
PullRequestWatchService.PullRequestWatchThreadNotFoundError,
PullRequestUrlInvalidError,
PullRequestTargetIncompleteError,
PullRequestHostRequiredError,
PullRequestUrlUnavailableError,
PullRequestUnavailableError,
]);

const SubscribeTool = Tool.make("t3_event_subscribe", {
description:
"Subscribe this thread to events. Phase 1 accepts a pull request URL or a thread id. Other selectors and external sources return a typed error and are not stored.",
parameters: EventSubscribeInput,
success: EventSubscription,
failure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Subscribe to events")
.annotate(Tool.Readonly, false)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true)
.annotate(Tool.OpenWorld, false)
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients);

const UnsubscribeTool = Tool.make("t3_event_unsubscribe", {
description: "Remove one of this thread's event subscriptions. Missing ids return removed=false.",
parameters: EventUnsubscribeInput,
success: Schema.Struct({ removed: Schema.Boolean }),
failure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Unsubscribe from events")
.annotate(Tool.Readonly, false)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true)
.annotate(Tool.OpenWorld, false)
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients);

const ListTool = Tool.make("t3_event_list", {
description: "List this thread's event subscriptions.",
parameters: Schema.Struct({}),
success: Schema.Struct({ subscriptions: Schema.Array(EventSubscription) }),
failure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "List event subscriptions")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true)
.annotate(Tool.OpenWorld, false)
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients);

export const EventsToolkit = Toolkit.make(SubscribeTool, UnsubscribeTool, ListTool);
Loading
Loading