Merge current MCP foundation

* codex/paperclip-public-mcp:
  test(shared): make the worktree port registry lock suite deterministic (#12798)
  fix(adapter-utils): make the directory merge lock crash test deterministic (#14881)
  feat(connections): make AgentMail a default connection with inline setup (#14772)
  fix(chat): hide ignored provider information (#14929)
  build(deps): bump aws-actions/configure-aws-credentials from 6.2.3 to 6.3.0 (#12966)

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-02 10:34:18 -05:00
commit a75c50f79f
94 files changed
+4126 -2196

No files matched your search

@@ -37,7 +37,7 @@
],
"guidanceMd": "Connect an AgentMail API key, then create or select an inbox for your agent. WebSocket receiving works without a public URL.",
"consoleLinks": {
"keys": "https://console.agentmail.to",
"keys": "https://console.agentmail.to/dashboard/api-keys",
"docs": "https://docs.agentmail.to/inboxes"
},
"riskTier": "S3",
@@ -13,7 +13,7 @@ export const CONNECTION_INTENT_AGENT_GUIDANCE = [
"- Do not use connection tools for arbitrary MCP URLs or unrelated work.",
].join("\n");
export const CONNECTIONS_SEARCH_TOOL_DESCRIPTION = "Search connections across tool, channel/email, and AI purposes with a service name or a natural-language description (up to 4000 characters). Results tolerate extra words, split names, and small typos. Choose the relevant match using its description, method purpose, and setupPath; tool methods use connection_request. Also discovers verified external aggregator apps. Use first when the user asks to connect a service, or when usable access is uncertain; follow the returned instruction and exact providerQuestion, if any. Do not use for arbitrary MCP URLs. Search is read-only.";
export const CONNECTIONS_SEARCH_TOOL_DESCRIPTION = "Search connections across tool, channel/email, and AI purposes with a service name or a natural-language description (up to 4000 characters). Results tolerate extra words, split names, and small typos. Choose the relevant match using its description and method purpose. Follow the returned instruction to present an inline setup card with connection_request or share the method's setupPath. Also discovers verified external aggregator apps. Use first when the user asks to connect a service, or when usable access is uncertain; follow the returned instruction and exact providerQuestion, if any. Do not use for arbitrary MCP URLs. Search is read-only.";
export const CONNECTION_REQUEST_TOOL_DESCRIPTION = "Request the service identifier returned by connections_search as available or needs_user_action. Follow the search instruction; aggregator routes require the saved provider-selection interaction ID. Only this tool creates the real setup card. If user action is needed, finish independent work, then yield without retrying or asking for credentials in comments.";
+1 -1
View File
@@ -118,7 +118,7 @@ export const INSTANCE_FEATURE_CATALOG: Record<InstanceFeatureKey, FeatureCatalog
enableChatConnectors: {
title: "Chat connectors",
description:
"Show experimental chat connector setup and Board surfaces. Existing connections keep running when hidden; GitHub and other tool connectors are unaffected.",
"Show experimental chat connector setup and Board surfaces. Existing connections keep running when hidden; AgentMail, GitHub tools, and other tool connectors are unaffected.",
tier: "managed",
cloudDefault: false,
selfHostedDefault: false,
@@ -28,7 +28,7 @@ export interface ConnectionSearchResultItem {
key: string;
label: string;
auth: "oauth" | "api_key" | "none";
/** Discovery is open across purposes; connection_request creates tool cards. */
/** AgentMail channel setup and tool methods support connection_request cards. */
purpose?: "tool" | "channel" | "ai";
/** Company-scoped setup destination for methods with a separate setup flow. */
setupPath?: string;
@@ -60,6 +60,8 @@ export interface ConnectionRequestResult {
export type ConnectionIntentSetupConnection = Pick<ToolConnection, "id" | "applicationId" | "name" | "status" | "enabled">;
export interface ConnectionIntentSetupOptions {
/** Resume this request's saved AgentMail account after a partial setup. */
emailSetup?: { credentialConnectionId: string | null; readyConnectionId: string | null };
aiConnection?: import("../ai-connections.js").AiConnectionBinding;
/** Legacy authentication stays unchanged until the normal validated agent update succeeds. */
aiConnectionRequiresAdoption?: boolean;
+14
View File
@@ -52,3 +52,17 @@ export interface EmailThreadSummary {
messages: EmailMessage[];
publications: EmailPublicationSummary[];
}
/** A missing inbox is not proof of availability: AgentMail hides other accounts. */
export interface EmailAddressCheckResult {
address: string;
status: "taken" | "unknown";
}
/** Metadata only, filtered by provider and the current user's credential grants. */
export interface EmailCredentialOption {
id: string;
label: string;
scope: "organization" | "pod" | "inbox" | "unavailable";
inboxId: string | null;
createdAt: string;
}
+2 -2
View File
@@ -1359,8 +1359,8 @@ export type ConnectionIntentPhase = "requested" | "authorizing" | "needs_retry";
export interface ConnectionIntentPayload {
version: 1;
upstreamService?: { slug: string; name: string; selectionInteractionId?: string };
/** Runtime authentication requests cannot be satisfied by tool credentials. */
purpose?: "ai";
/** AI authentication and inbox setup cannot be satisfied by tool credentials. */
purpose?: "ai" | "channel";
serviceSlug: string;
serviceName: string;
serviceLogoUrl?: string | null;
+6
View File
@@ -2,6 +2,12 @@ import { z } from "zod";
const address = z.string().trim().email().max(320);
const addresses = z.array(address).max(50);
export const emailAddressCheckSchema = z.object({
username: z.string().trim().toLowerCase().regex(/^[a-z0-9][a-z0-9._-]*$/).max(64),
domain: z.string().trim().toLowerCase().max(253).regex(/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$/),
}).strict();
export type EmailAddressCheckInput = z.infer<typeof emailAddressCheckSchema>;
export const emailEndpointSetupSchema = z
.object({
assignedAgentId: z.string().uuid(),
+1 -1
View File
@@ -1111,7 +1111,7 @@ const connectionIntentBrandAssetSchema = z
export const connectionIntentPayloadSchema = z
.object({
upstreamService: z.object({ slug: z.string().min(1).max(120), name: z.string().min(1).max(160), selectionInteractionId: z.string().guid().optional() }).strict().optional(),
purpose: z.literal("ai").optional(),
purpose: z.enum(["ai", "channel"]).optional(),
version: z.literal(1),
serviceSlug: z.string().trim().min(1).max(120),
serviceName: z.string().trim().min(1).max(160),
@@ -2,6 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { Worker } from "node:worker_threads";
import { afterEach, describe, expect, it } from "vitest";
import {
withWorktreePortRegistryLock,
@@ -16,12 +17,92 @@ function makeTemporaryRoot(): string {
return root;
}
function deferred(): { promise: Promise<void>; resolve: () => void } {
let resolve!: () => void;
const promise = new Promise<void>((done) => {
resolve = done;
// Answers the same one-exchange ownership probe protocol the real lock
// heartbeat serves, so a test can hold a lock's "owner is alive and
// responsive" state without a live heartbeat thread touching the lock's
// mtime in the background. This runs on its own worker thread, not the
// main thread, because the code under test blocks the calling thread
// (Atomics.wait) while it waits for a probe answer; a same-thread server
// could never respond to its own blocked caller.
// The worker posts an "owned" message back to the main thread each time it
// answers a probe with "owned". The test waits on that message instead of a
// fixed delay, so the assertion that follows only runs after the probe has
// actually answered at least one ownership check, not merely after some
// wall-clock time.
const FAKE_OWNERSHIP_PROBE_SOURCE = `
const net = require("node:net");
const { parentPort, workerData } = require("node:worker_threads");
const control = new Int32Array(workerData.control);
const server = net.createServer((socket) => {
socket.once("data", (candidate) => {
const answer = candidate.toString("utf8") === workerData.token ? "owned" : "denied";
if (answer === "owned") parentPort.postMessage("owned");
socket.end(answer);
});
return { promise, resolve };
});
server.once("error", () => {
Atomics.store(control, 0, -1);
Atomics.notify(control, 0);
});
server.listen(0, "127.0.0.1", () => {
const address = server.address();
Atomics.store(control, 1, address.port);
Atomics.store(control, 0, 1);
Atomics.notify(control, 0);
});
parentPort.once("message", () => {
server.close(() => process.exit(0));
});
`;
function startFakeOwnershipProbe(token: string): {
port: number;
waitForOwnedResponse: (timeoutMs?: number) => Promise<void>;
close: () => Promise<void>;
} {
const control = new Int32Array(new SharedArrayBuffer(8));
const worker = new Worker(FAKE_OWNERSHIP_PROBE_SOURCE, {
eval: true,
execArgv: [],
workerData: { control: control.buffer, token },
});
Atomics.wait(control, 0, 0, 5_000);
const port = Atomics.load(control, 1);
if (Atomics.load(control, 0) !== 1 || port <= 0) {
void worker.terminate();
throw new Error("The fake ownership probe failed to start.");
}
let ownedResponseSeen = false;
const ownedWaiters: Array<() => void> = [];
worker.on("message", (message: unknown) => {
if (message !== "owned") return;
ownedResponseSeen = true;
for (const resolveWaiter of ownedWaiters.splice(0)) resolveWaiter();
});
return {
port,
// Resolves once the probe has answered "owned" at least once. Falls
// straight through when that has already happened, and otherwise waits
// for the worker's next "owned" message.
waitForOwnedResponse: (timeoutMs = 5_000): Promise<void> => {
if (ownedResponseSeen) return Promise.resolve();
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error("Timed out waiting for the fake ownership probe to answer \"owned\"."));
}, timeoutMs);
ownedWaiters.push(() => {
clearTimeout(timer);
resolve();
});
});
},
close: () => new Promise<void>((resolve) => {
worker.once("exit", () => resolve());
worker.postMessage("stop");
}),
};
}
afterEach(() => {
@@ -34,36 +115,70 @@ describe("worktree port registry lock", () => {
it("does not reclaim a stale lock while its fallback ownership probe responds", async () => {
const homeDir = makeTemporaryRoot();
const lockPath = path.join(homeDir, ".worktree-port-reservations.lock");
const firstEntered = deferred();
const releaseFirst = deferred();
let secondEntered = false;
const token = "fixed-owner-token";
const probe = startFakeOwnershipProbe(token);
let probeClosed = false;
const closeProbeOnce = async (): Promise<void> => {
if (probeClosed) return;
probeClosed = true;
await probe.close();
};
let second: Promise<void> | undefined;
const first = withWorktreePortRegistryLock(homeDir, async () => {
fs.renameSync(path.join(lockPath, "owner.json"), path.join(lockPath, "owner.unavailable.json"));
const backupOwnerPath = path.join(lockPath, "owner.backup.json");
const owner = JSON.parse(fs.readFileSync(backupOwnerPath, "utf8"));
fs.writeFileSync(backupOwnerPath, `${JSON.stringify({
...owner,
processIdentity: "unavailable-process-identity",
})}\n`);
try {
// Build the contended state directly instead of holding the lock through
// a real withWorktreePortRegistryLock call. A real call starts a live
// heartbeat that rewrites the lock's mtime once a second on a worker
// thread. That refresh runs concurrently with, and can land inside, the
// gap between this test backdating the mtime and reading it back, which
// made the assertion below fail at random under CPU contention. With no
// live heartbeat, nothing touches the mtime until this test says so.
fs.mkdirSync(lockPath);
fs.writeFileSync(
path.join(lockPath, "owner.json"),
`${JSON.stringify({
version: 1,
pid: process.pid,
// Deliberately wrong, so a reclaim can only be blocked by the probe
// answering "owned" below, not by the process-identity fallback.
processIdentity: "mismatched-process-identity",
probePort: probe.port,
token,
})}\n`,
);
const oldTimestamp = new Date(Date.now() - 10_000);
fs.utimesSync(lockPath, oldTimestamp, oldTimestamp);
firstEntered.resolve();
await releaseFirst.promise;
});
await firstEntered.promise;
expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeGreaterThan(5_000);
// Nothing refreshes the lock after this point, so its age only grows.
expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeGreaterThan(5_000);
const second = withWorktreePortRegistryLock(homeDir, async () => {
secondEntered = true;
});
await delay(100);
let secondEntered = false;
second = withWorktreePortRegistryLock(homeDir, async () => {
secondEntered = true;
});
// Wait for the fake probe to actually answer "owned" before checking
// secondEntered. A fixed delay can fire before the probe worker gets
// scheduled under processor contention, letting the assertion below
// pass without proving the reclaim was blocked by a real "owned"
// answer.
await probe.waitForOwnedResponse();
expect(secondEntered).toBe(false);
releaseFirst.resolve();
await Promise.all([first, second]);
expect(secondEntered).toBe(true);
expect(secondEntered).toBe(false);
// Retire the owner: the probe stops answering, so the next reclaim
// attempt falls through to the process-identity check, which the
// mismatched identity above fails, and the lock is reclaimed.
await closeProbeOnce();
await second;
expect(secondEntered).toBe(true);
} finally {
// Run this unconditionally. If an assertion above throws, the fake
// probe's worker thread must still stop, and the pending lock attempt
// must still settle, so a failure here does not leak a worker thread
// or leave an unawaited rejection for a later test file to report.
await closeProbeOnce();
await second?.catch(() => {});
}
}, 10_000);
it("refreshes the lease throughout an async critical section", async () => {
@@ -71,8 +186,27 @@ describe("worktree port registry lock", () => {
const lockPath = path.join(homeDir, ".worktree-port-reservations.lock");
await withWorktreePortRegistryLock(homeDir, async () => {
await delay(5_250);
expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeLessThan(2_000);
// Count refreshes instead of only checking recency. A recency check
// alone tolerates a regressed heartbeat interval: a tick every 3000 ms
// or 4000 ms still keeps the lock's age under the 5000 ms staleness
// threshold at the end of this window, so it would pass. Counting the
// distinct mtimes the lock passes through does not depend on when a
// tick lands, only on how many land, so it still catches a regressed
// interval.
const observedTimestamps = new Set<number>();
const pollDeadline = Date.now() + 5_250;
while (Date.now() < pollDeadline) {
observedTimestamps.add(fs.statSync(lockPath).mtimeMs);
await delay(100);
}
// A 1000 ms heartbeat interval produces about 6 distinct values here
// (the initial touch plus about 5 refreshes). A regressed 3000 ms
// interval produces only 2, so this catches the regression that a
// recency-only check would miss.
expect(observedTimestamps.size).toBeGreaterThanOrEqual(3);
// The heartbeat's other correctness job is to keep the lock's mtime
// below the staleness threshold (5 seconds) while the lock is held.
expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeLessThan(5_000);
});
expect(fs.existsSync(lockPath)).toBe(false);
@@ -139,7 +273,10 @@ describe("worktree port registry lock", () => {
const oldTimestamp = new Date(Date.now() - 10_000);
fs.utimesSync(lockPath, oldTimestamp, oldTimestamp);
Atomics.wait(blocker, 0, 0, 1_500);
expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeLessThan(1_250);
// Same reasoning as the async critical-section test above: assert
// against the staleness threshold the heartbeat exists to defend,
// not a tight margin coupled to one heartbeat interval.
expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeLessThan(5_000);
});
expect(fs.existsSync(lockPath)).toBe(false);