feat(mcp) [split 2/8]: add governed access contracts (#9557)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Governed MCP access spans contracts, runtime enforcement, adapters,
UI surfaces, and operator verification
> - The parity reference PR #9534 is too large for effective automated
or human review
> - The feature therefore needs a linear stack whose individual diffs
stay below the 100-file review limit
> - This pull request is split 2/8 and focuses on database schema and
shared governance contracts
> - The benefit is a standalone, testable review boundary while
preserving byte-for-byte parity at the top of the stack

## Linked Issues or Issue Description

- Related parity reference: #9534
- Problem: The governed access model needs additive persistence and
synchronized shared types before server enforcement can compile.
- Proposed solution: Adds migrations 0148–0169, tool-access and Smoke
Lab schema, shared types/validators/gallery helpers, and the minimal
compile-required contract consumers identified by boundary testing.
- Alternatives considered: keeping #9534 as one 403-file review, or
rewriting the feature to manufacture seams; both were rejected in favor
of path extraction plus compile-driven boundary moves.
- Roadmap alignment: this advances the existing governed MCP/tool-access
work already represented by #9534; it does not introduce a separate
roadmap initiative.
- Stack position: base branch is `pap10341-split/01-demo-servers`.
- Merge policy: merge bottom-up, in order, only after the complete
eight-PR stack has been reviewed and the top-of-stack parity gate
remains empty.
- Requested review: QA for migrations/validators; Greptile on every PR.

## What Changed

- Adds migrations 0148–0169, tool-access and Smoke Lab schema, shared
types/validators/gallery helpers, and the minimal compile-required
contract consumers identified by boundary testing.
- Keeps this PR below 100 changed files and independently typecheckable.
- Preserves the final tree from #9534 when combined with the other seven
stack levels.

## Verification

- `pnpm typecheck` — passed, including migration numbering and safety
checks
- `pnpm --filter @paperclipai/db test` — passed
- `pnpm --filter @paperclipai/shared test` — passed

## Risks

- Migration or contract mistakes could affect every upper layer; all
migrations are additive/idempotent and compile consumers are included in
this boundary.
- Stack risk: merging out of order can expose incomplete layers;
mitigate by following the documented bottom-up merge policy.
- Parity risk: later edits to an intermediate branch can drift from
#9534; mitigate by re-running the empty top-of-stack diff before merge.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex, exact model ID `gpt-5.4`; runtime-managed context
window; medium reasoning with repository, shell, Git, GitHub CLI, and
code-execution tools enabled.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] Internal references are omitted except the execution-plan link
explicitly required for this coordinated split stack
- [x] My branch name describes the change and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge


## Stack Coordination

- Internal execution plan:
[PAP-13874](/PAP/issues/PAP-13874#document-plan)
- Parity reference: #9534
- Stack: #9556 → #9557 → #9558 → #9559 → #9560 → #9561 → #9562 → #9563
- Merge bottom-up only after full-stack review and an empty parity diff
at #9563.

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-07-14 12:57:20 -05:00
1 parent 7b35de65aa
commit 1de0a3bb1e
81 files changed
+7277 -307

No files matched your search

+18
View File
@@ -23,6 +23,24 @@ export const API = {
goals: `${API_PREFIX}/goals`,
approvals: `${API_PREFIX}/approvals`,
secrets: `${API_PREFIX}/secrets`,
tools: `${API_PREFIX}/companies/:companyId/tools`,
toolExamples: `${API_PREFIX}/companies/:companyId/tools/examples`,
toolApplications: `${API_PREFIX}/companies/:companyId/tools/applications`,
toolConnections: `${API_PREFIX}/companies/:companyId/tools/connections`,
toolCatalog: `${API_PREFIX}/companies/:companyId/tools/catalog`,
toolProfiles: `${API_PREFIX}/companies/:companyId/tools/profiles`,
toolPolicies: `${API_PREFIX}/companies/:companyId/tools/policies`,
toolAudit: `${API_PREFIX}/companies/:companyId/tools/audit`,
toolRuntimeSlots: `${API_PREFIX}/companies/:companyId/tools/runtime-slots`,
toolRuntimeSlotStop: `${API_PREFIX}/companies/:companyId/tools/runtime-slots/:id/stop`,
toolRuntimeSlotRestart: `${API_PREFIX}/companies/:companyId/tools/runtime-slots/:id/restart`,
toolRuntimeHealth: `${API_PREFIX}/companies/:companyId/tools/runtime-health`,
toolGateway: `${API_PREFIX}/tool-gateway`,
smokeLab: `${API_PREFIX}/companies/:companyId/smoke-lab`,
smokeLabServices: `${API_PREFIX}/companies/:companyId/smoke-lab/services`,
smokeLabInstallFixtures: `${API_PREFIX}/companies/:companyId/smoke-lab/install-fixtures`,
smokeLabRuns: `${API_PREFIX}/companies/:companyId/smoke-lab/runs`,
smokeLabRunSteps: `${API_PREFIX}/companies/:companyId/smoke-lab/runs/:runId/steps`,
userSecretDefinitions: `${API_PREFIX}/companies/:companyId/user-secret-definitions`,
userSecretDefinition: `${API_PREFIX}/companies/:companyId/user-secret-definitions/:definitionId`,
userSecretDefinitionCoverage: `${API_PREFIX}/companies/:companyId/user-secret-definitions/:definitionId/coverage`,
+285
View File
@@ -659,6 +659,7 @@ export const SECRET_BINDING_TARGET_TYPES = [
"plugin",
"issue",
"run",
"tool_connection",
"system",
] as const;
export type SecretBindingTargetType = (typeof SECRET_BINDING_TARGET_TYPES)[number];
@@ -674,6 +675,55 @@ export const SECRET_ACCESS_OUTCOMES = [
] as const;
export type SecretAccessOutcome = (typeof SECRET_ACCESS_OUTCOMES)[number];
export const SECRET_PROJECTION_CLASSES = ["unclassified", "class_3_static_lease"] as const;
export type SecretProjectionClass = (typeof SECRET_PROJECTION_CLASSES)[number];
export const CLASS3_STATIC_LEASE_ALLOWLIST = [
{
key: "slack.bot_token",
label: "Slack bot token",
targetType: "agent",
configPath: "env.SLACK_BOT_TOKEN",
envKey: "SLACK_BOT_TOKEN",
},
{
key: "slack.bot_token",
label: "Slack bot token",
targetType: "routine",
configPath: "env.SLACK_BOT_TOKEN",
envKey: "SLACK_BOT_TOKEN",
},
{
key: "slack.bot_token",
label: "Slack bot token governance connection",
targetType: "tool_connection",
configPath: "credentials.bot_token",
envKey: "SLACK_BOT_TOKEN",
},
{
key: "discord.bot_token",
label: "Discord bot token",
targetType: "agent",
configPath: "env.DISCORD_BOT_TOKEN",
envKey: "DISCORD_BOT_TOKEN",
},
{
key: "discord.bot_token",
label: "Discord bot token",
targetType: "routine",
configPath: "env.DISCORD_BOT_TOKEN",
envKey: "DISCORD_BOT_TOKEN",
},
{
key: "discord.bot_token",
label: "Discord bot token governance connection",
targetType: "tool_connection",
configPath: "credentials.bot_token",
envKey: "DISCORD_BOT_TOKEN",
},
] as const;
export type Class3StaticLeaseAllowlistKey = (typeof CLASS3_STATIC_LEASE_ALLOWLIST)[number]["key"];
export const STORAGE_PROVIDERS = ["local_disk", "s3"] as const;
export type StorageProvider = (typeof STORAGE_PROVIDERS)[number];
@@ -860,6 +910,12 @@ export const PERMISSION_KEYS = [
"skills:create",
"skills:suggest-changes",
"environments:manage",
"tools:admin",
"tools:manage_connections",
"tools:manage_profiles",
"tools:view_audit",
"tools:use",
"tools:manage_runtime",
"users:invite",
"users:manage_permissions",
"tasks:assign",
@@ -870,6 +926,235 @@ export const PERMISSION_KEYS = [
] as const;
export type PermissionKey = (typeof PERMISSION_KEYS)[number];
export const TOOL_APPLICATION_TYPES = ["mcp_http", "mcp_stdio", "paperclip_plugin", "a2a"] as const;
export type ToolApplicationType = (typeof TOOL_APPLICATION_TYPES)[number];
export const TOOL_APPLICATION_STATUSES = ["draft", "active", "disabled", "archived"] as const;
export type ToolApplicationStatus = (typeof TOOL_APPLICATION_STATUSES)[number];
export const TOOL_CONNECTION_KINDS = ["managed"] as const;
export type ToolConnectionKind = (typeof TOOL_CONNECTION_KINDS)[number];
export const TOOL_CONNECTION_HEALTH_STATUSES = [
"unknown",
"healthy",
"degraded",
"failed",
"unchecked",
"ok",
"error",
"missing_secret",
] as const;
export type ToolConnectionHealthStatus = (typeof TOOL_CONNECTION_HEALTH_STATUSES)[number];
/**
* Health states that mean an app needs the user's attention (a bad/missing key
* or a degraded connection). Single source of truth shared by the needs-
* attention aggregation and the prosumer Apps surfaces so their counts agree.
*/
export const TOOL_CONNECTION_ATTENTION_HEALTH_STATUSES: readonly ToolConnectionHealthStatus[] = [
"degraded",
"failed",
"error",
"missing_secret",
];
export function isToolConnectionAttentionHealth(status: ToolConnectionHealthStatus): boolean {
return TOOL_CONNECTION_ATTENTION_HEALTH_STATUSES.includes(status);
}
export const TOOL_CATALOG_ENTRY_KINDS = ["tool", "resource", "prompt"] as const;
export type ToolCatalogEntryKind = (typeof TOOL_CATALOG_ENTRY_KINDS)[number];
export const TOOL_CATALOG_ENTRY_STATUSES = ["active", "disabled", "quarantined", "removed"] as const;
export type ToolCatalogEntryStatus = (typeof TOOL_CATALOG_ENTRY_STATUSES)[number];
export const TOOL_RISK_LEVELS = ["low", "medium", "high", "critical", "read", "write", "destructive"] as const;
export type ToolRiskLevel = (typeof TOOL_RISK_LEVELS)[number];
export const TOOL_PROFILE_STATUSES = ["draft", "active", "disabled", "archived"] as const;
export type ToolProfileStatus = (typeof TOOL_PROFILE_STATUSES)[number];
export const TOOL_PROFILE_DEFAULT_ACTIONS = ["deny", "allow"] as const;
export type ToolProfileDefaultAction = (typeof TOOL_PROFILE_DEFAULT_ACTIONS)[number];
export const TOOL_PROFILE_ENTRY_SELECTOR_TYPES = [
"application",
"connection",
"catalog_entry",
"tool_name",
"risk_level",
] as const;
export type ToolProfileEntrySelectorType = (typeof TOOL_PROFILE_ENTRY_SELECTOR_TYPES)[number];
export const TOOL_PROFILE_ENTRY_EFFECTS = ["include", "exclude"] as const;
export type ToolProfileEntryEffect = (typeof TOOL_PROFILE_ENTRY_EFFECTS)[number];
export const TOOL_PROFILE_BINDING_TARGET_TYPES = ["company", "agent", "project", "routine", "issue", "gateway"] as const;
export type ToolProfileBindingTargetType = (typeof TOOL_PROFILE_BINDING_TARGET_TYPES)[number];
export const TOOL_MCP_GATEWAY_STATUSES = ["draft", "active", "disabled", "archived"] as const;
export type ToolMcpGatewayStatus = (typeof TOOL_MCP_GATEWAY_STATUSES)[number];
export const TOOL_MCP_GATEWAY_DEFAULT_PROFILE_MODES = [
"gateway_only",
"inherit_context_then_gateway",
"gateway_then_context",
] as const;
export type ToolMcpGatewayDefaultProfileMode = (typeof TOOL_MCP_GATEWAY_DEFAULT_PROFILE_MODES)[number];
export const TOOL_MCP_GATEWAY_CONTEXT_SCOPE_TYPES = [
"none",
"company",
"project",
"routine",
"issue",
"agent",
] as const;
export type ToolMcpGatewayContextScopeType = (typeof TOOL_MCP_GATEWAY_CONTEXT_SCOPE_TYPES)[number];
export const TOOL_MCP_GATEWAY_TOKEN_SUBJECT_TYPES = ["gateway_client", "heartbeat_run", "board_user", "agent"] as const;
export type ToolMcpGatewayTokenSubjectType = (typeof TOOL_MCP_GATEWAY_TOKEN_SUBJECT_TYPES)[number];
export const TOOL_MCP_GATEWAY_TOKEN_ACTIONS = ["tools/list", "tools/call"] as const;
export type ToolMcpGatewayTokenAction = (typeof TOOL_MCP_GATEWAY_TOKEN_ACTIONS)[number];
export const CONNECTION_TOKEN_ISSUANCE_PATHS = ["exchange", "oauth_access", "static"] as const;
export type ConnectionTokenIssuancePath = (typeof CONNECTION_TOKEN_ISSUANCE_PATHS)[number];
export const CONNECTION_TOKEN_ISSUANCE_OUTCOMES = [
"success",
"denied",
"rate_limited",
"use_env_lease",
"upstream_error",
"failure",
] as const;
export type ConnectionTokenIssuanceOutcome = (typeof CONNECTION_TOKEN_ISSUANCE_OUTCOMES)[number];
export const TOOL_POLICY_TYPES = [
"allow",
"block",
"require_approval",
"trust_rule",
"rate_limit",
] as const;
export type ToolPolicyType = (typeof TOOL_POLICY_TYPES)[number];
export const TOOL_POLICY_DECISIONS = ["allow", "deny", "require_approval", "rate_limited", "defer_runtime"] as const;
export type ToolPolicyDecision = (typeof TOOL_POLICY_DECISIONS)[number];
export const TOOL_INVOCATION_STATUSES = [
"pending",
"authorized",
"denied",
"awaiting_approval",
"executing",
"succeeded",
"failed",
"cancelled",
"timed_out",
"rate_limited",
] as const;
export type ToolInvocationStatus = (typeof TOOL_INVOCATION_STATUSES)[number];
export const TOOL_INVOCATION_APPROVAL_STATES = [
"not_required",
"required",
"pending",
"approved",
"rejected",
"expired",
] as const;
export type ToolInvocationApprovalState = (typeof TOOL_INVOCATION_APPROVAL_STATES)[number];
export const TOOL_ACTION_REQUEST_STATUSES = [
"pending",
"approved",
"executing",
"rejected",
"expired",
"cancelled",
"executed",
"failed",
] as const;
export type ToolActionRequestStatus = (typeof TOOL_ACTION_REQUEST_STATUSES)[number];
export const TOOL_AUDIT_EVENT_TYPES = [
"discovery",
"policy_decision",
"invocation_created",
"call_started",
"call_completed",
"call_failed",
"call_denied",
"approval_requested",
"approval_resolved",
"session_revoked",
"trust_rule_created",
"trust_rule_revoked",
"trust_rule_used",
"runtime_started",
"runtime_stopped",
"rate_limited",
] as const;
export type ToolAuditEventType = (typeof TOOL_AUDIT_EVENT_TYPES)[number];
export const TOOL_AUDIT_OUTCOMES = ["pending", "success", "failure", "denied", "timeout", "cancelled"] as const;
export type ToolAuditOutcome = (typeof TOOL_AUDIT_OUTCOMES)[number];
/**
* Connection-level lifecycle events surfaced on the per-app Activity tab
* alongside tool-call events (PAP-11284). These are derived from the
* company activity log rows scoped to a single tool connection.
*/
export const TOOL_CONNECTION_LIFECYCLE_EVENT_TYPES = [
"app_connected",
"app_paused",
"app_resumed",
"allowlist_changed",
"reconnected",
"disconnected",
"actions_quarantined",
] as const;
export type ToolConnectionLifecycleEventType = (typeof TOOL_CONNECTION_LIFECYCLE_EVENT_TYPES)[number];
export const TOOL_RUNTIME_KINDS = ["remote_session", "local_stdio"] as const;
export type ToolRuntimeKind = (typeof TOOL_RUNTIME_KINDS)[number];
export const TOOL_RUNTIME_SLOT_STATUSES = ["starting", "running", "idle", "stopped", "failed", "disabled", "error"] as const;
export type ToolRuntimeSlotStatus = (typeof TOOL_RUNTIME_SLOT_STATUSES)[number];
export const TOOL_RATE_LIMIT_WINDOW_KINDS = ["minute", "hour", "day", "month"] as const;
export type ToolRateLimitWindowKind = (typeof TOOL_RATE_LIMIT_WINDOW_KINDS)[number];
export const TOOL_ACCESS_ACTIVITY_ACTIONS = [
"tool_application.created",
"tool_application.updated",
"tool_application.archived",
"tool_connection.created",
"tool_connection.updated",
"tool_connection.tested",
"tool_connection.catalog_refreshed",
"tool_profile.created",
"tool_profile.updated",
"tool_profile.duplicated",
"tool_profile.deleted",
"tool_profile.new_tools_reviewed",
"tool_profile.bound",
"tool_profile.unbound",
"tool_policy.created",
"tool_policy.updated",
"tool_policy.disabled",
"tool_trust_rule.created",
"tool_trust_rule.revoked",
"tool_runtime_slot.started",
"tool_runtime_slot.stopped",
"tool_action_request.created",
"tool_action_request.resolved",
] as const;
export type ToolAccessActivityAction = (typeof TOOL_ACCESS_ACTIVITY_ACTIONS)[number];
// ---------------------------------------------------------------------------
// Plugin System — see doc/plugins/PLUGIN_SPEC.md for the full specification
// ---------------------------------------------------------------------------
@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import {
connectionDisplaySecondaryHint,
humanizeConnectionDisplayName,
} from "./humanize-connection.js";
describe("humanizeConnectionDisplayName", () => {
it("hides raw IPs / hosts behind a generic label", () => {
expect(humanizeConnectionDisplayName("127.0.0.1")).toBe("Custom app");
expect(humanizeConnectionDisplayName("127.0.0.1:8931")).toBe("Custom app");
expect(humanizeConnectionDisplayName("localhost")).toBe("Custom app");
expect(humanizeConnectionDisplayName("example.com:8080")).toBe("Custom app");
expect(humanizeConnectionDisplayName("https://mcp.example.com/sse")).toBe("Custom app");
});
it("drops the `Plugin:` prefix and title-cases the package leaf", () => {
expect(humanizeConnectionDisplayName("Plugin: paperclipai.plugin-briefs")).toBe("Briefs");
expect(humanizeConnectionDisplayName("Plugin: acme.plugin-weekly-report")).toBe(
"Weekly Report",
);
});
it("turns `vendor:tool` ids into Title Case With Spaces", () => {
expect(humanizeConnectionDisplayName("mcp-remote-fixture:update_note")).toBe("Update Note");
expect(humanizeConnectionDisplayName("github:create_issue")).toBe("Create Issue");
});
it("title-cases a bare snake/kebab identifier", () => {
expect(humanizeConnectionDisplayName("update_note")).toBe("Update Note");
expect(humanizeConnectionDisplayName("send-email")).toBe("Send Email");
});
it("passes through normal, already-human app names", () => {
expect(humanizeConnectionDisplayName("Zapier")).toBe("Zapier");
expect(humanizeConnectionDisplayName("Notion")).toBe("Notion");
expect(humanizeConnectionDisplayName("Google Drive")).toBe("Google Drive");
});
it("prefers an explicit title when provided", () => {
expect(
humanizeConnectionDisplayName("mcp-remote-fixture:update_note", { title: "Update note" }),
).toBe("Update note");
// Blank/whitespace titles fall back to derivation.
expect(humanizeConnectionDisplayName("update_note", { title: " " })).toBe("Update Note");
});
it("accepts a connection-like object and handles empty input", () => {
expect(humanizeConnectionDisplayName({ name: "Plugin: acme.plugin-briefs" })).toBe("Briefs");
expect(humanizeConnectionDisplayName("")).toBe("Custom app");
expect(humanizeConnectionDisplayName(null)).toBe("Custom app");
});
});
describe("connectionDisplaySecondaryHint", () => {
it("surfaces `hosted at …` only for network addresses", () => {
expect(connectionDisplaySecondaryHint("127.0.0.1")).toBe("hosted at 127.0.0.1");
expect(connectionDisplaySecondaryHint("127.0.0.1:8931")).toBe("hosted at 127.0.0.1:8931");
expect(connectionDisplaySecondaryHint({ name: "Zapier" })).toBeNull();
expect(connectionDisplaySecondaryHint("Plugin: acme.plugin-briefs")).toBeNull();
expect(connectionDisplaySecondaryHint("")).toBeNull();
});
});
+103
View File
@@ -0,0 +1,103 @@
/**
* Humanize engineering connection / tool identifiers for the prosumer Apps
* surfaces (PAP-10897).
*
* `connection.name` (and tool ids) can carry raw IPs, `Plugin:` prefixes with
* dotted package paths, and `vendor:tool` ids. None of that vocabulary may leak
* into `/apps`, `/apps/attention`, or the App-detail header — only `/apps/advanced`
* is allowed to show the raw identifiers. This module turns those identifiers
* into recognizable, plain-language labels.
*/
export interface HumanizableConnection {
name: string;
}
type ConnectionLike = HumanizableConnection | string | null | undefined;
function rawNameOf(input: ConnectionLike): string {
return (typeof input === "string" ? input : (input?.name ?? "")).trim();
}
/** IP / URL / host:port / localhost — anything that reads as a network address. */
function looksLikeNetworkAddress(raw: string): boolean {
const v = raw.toLowerCase();
if (v.includes("://")) return true; // any URL
if (v === "localhost" || v.startsWith("localhost:")) return true;
if (/^\d{1,3}(\.\d{1,3}){3}(:\d+)?$/.test(v)) return true; // IPv4 (optional :port)
if (/^[a-z0-9.-]+:\d+$/.test(v)) return true; // host:port
return false;
}
/** Title-case a snake/kebab/dotted identifier: `update_note` → `Update Note`. */
function titleCaseIdentifier(value: string): string {
return value
.split(/[\s._-]+/)
.filter(Boolean)
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(" ");
}
/** `Plugin: paperclipai.plugin-briefs` → `Briefs`; null when not a plugin label. */
function pluginPackageLabel(raw: string): string | null {
const match = /^plugin:\s*(.+)$/i.exec(raw);
if (!match) return null;
let leaf = match[1].trim();
// Keep the package leaf only: `paperclipai.plugin-briefs` → `plugin-briefs`.
leaf = leaf.slice(leaf.lastIndexOf(".") + 1);
// Drop the `plugin-` scaffolding leftover: `plugin-briefs` → `briefs`.
leaf = leaf.replace(/^plugin[-_]/i, "");
return titleCaseIdentifier(leaf) || "Custom app";
}
/**
* Turn an app/connection identifier (or a tool id) into a prosumer-friendly
* label. Pass `options.title` (e.g. a catalog entry's `title`) to prefer a
* known human title over any derivation.
*
* `127.0.0.1` → `Custom app`
* `Plugin: paperclipai.plugin-briefs` → `Briefs`
* `mcp-remote-fixture:update_note` → `Update Note`
* `Zapier` / `Notion` → unchanged
*/
export function humanizeConnectionDisplayName(
input: ConnectionLike,
options: { title?: string | null } = {},
): string {
const title = options.title?.trim();
if (title) return title; // a real, human title always wins
const raw = rawNameOf(input);
if (!raw) return "Custom app";
if (looksLikeNetworkAddress(raw)) return "Custom app";
const pluginLabel = pluginPackageLabel(raw);
if (pluginLabel) return pluginLabel;
// `vendor:tool` id (e.g. `mcp-remote-fixture:update_note`) → tool segment.
if (raw.includes(":") && !raw.includes("://")) {
const tool = raw.slice(raw.lastIndexOf(":") + 1).trim();
if (tool) return titleCaseIdentifier(tool);
}
// Already human (a space or any capital) → pass through untouched.
if (/\s/.test(raw) || /[A-Z]/.test(raw)) return raw;
// Bare snake/kebab/dotted identifier → Title Case With Spaces.
if (/[._-]/.test(raw)) return titleCaseIdentifier(raw);
return raw;
}
/**
* Optional secondary line for the App-detail page only: when the raw name is a
* network address we hide it from the header but may still show `hosted at …`
* underneath as a small trust/clarity hint. Returns null when there's nothing
* worth surfacing.
*/
export function connectionDisplaySecondaryHint(input: ConnectionLike): string | null {
const raw = rawNameOf(input);
if (raw && looksLikeNetworkAddress(raw)) return `hosted at ${raw}`;
return null;
}
+327
View File
@@ -133,6 +133,21 @@ export {
type SourceTrustPromotionSource,
type SourceTrustMetadata,
} from "./trust-policy.js";
export {
TOOL_APP_GALLERY,
getToolAppGalleryEntry,
getToolAppGalleryEntryForUrl,
type AppGalleryAuthKind,
type AppGalleryCredentialField,
type AppGalleryEntry,
type AppGalleryKey,
type AppGalleryTransportTemplate,
} from "./tool-app-gallery.js";
export {
humanizeConnectionDisplayName,
connectionDisplaySecondaryHint,
type HumanizableConnection,
} from "./humanize-connection.js";
export {
COMPANY_STATUSES,
DEFAULT_COMPANY_ATTACHMENT_MAX_BYTES,
@@ -229,6 +244,8 @@ export {
SECRET_PROVIDERS,
SECRET_PROVIDER_CONFIG_STATUSES,
SECRET_PROVIDER_CONFIG_HEALTH_STATUSES,
SECRET_PROJECTION_CLASSES,
CLASS3_STATIC_LEASE_ALLOWLIST,
SECRET_SCOPES,
STORAGE_PROVIDERS,
BILLING_TYPES,
@@ -258,6 +275,39 @@ export {
JOIN_REQUEST_TYPES,
JOIN_REQUEST_STATUSES,
PERMISSION_KEYS,
TOOL_ACTION_REQUEST_STATUSES,
TOOL_APPLICATION_STATUSES,
TOOL_APPLICATION_TYPES,
TOOL_AUDIT_EVENT_TYPES,
TOOL_AUDIT_OUTCOMES,
TOOL_CATALOG_ENTRY_KINDS,
TOOL_CATALOG_ENTRY_STATUSES,
TOOL_CONNECTION_HEALTH_STATUSES,
TOOL_CONNECTION_ATTENTION_HEALTH_STATUSES,
isToolConnectionAttentionHealth,
TOOL_CONNECTION_KINDS,
TOOL_CONNECTION_LIFECYCLE_EVENT_TYPES,
TOOL_INVOCATION_APPROVAL_STATES,
TOOL_INVOCATION_STATUSES,
TOOL_MCP_GATEWAY_CONTEXT_SCOPE_TYPES,
TOOL_MCP_GATEWAY_DEFAULT_PROFILE_MODES,
TOOL_MCP_GATEWAY_STATUSES,
TOOL_MCP_GATEWAY_TOKEN_ACTIONS,
TOOL_MCP_GATEWAY_TOKEN_SUBJECT_TYPES,
CONNECTION_TOKEN_ISSUANCE_PATHS,
CONNECTION_TOKEN_ISSUANCE_OUTCOMES,
TOOL_POLICY_DECISIONS,
TOOL_POLICY_TYPES,
TOOL_PROFILE_BINDING_TARGET_TYPES,
TOOL_PROFILE_DEFAULT_ACTIONS,
TOOL_PROFILE_ENTRY_EFFECTS,
TOOL_PROFILE_ENTRY_SELECTOR_TYPES,
TOOL_PROFILE_STATUSES,
TOOL_RATE_LIMIT_WINDOW_KINDS,
TOOL_RISK_LEVELS,
TOOL_RUNTIME_KINDS,
TOOL_RUNTIME_SLOT_STATUSES,
TOOL_ACCESS_ACTIVITY_ACTIONS,
PLUGIN_API_VERSION,
PLUGIN_STATUSES,
PLUGIN_CATEGORIES,
@@ -370,6 +420,8 @@ export {
type SecretProvider,
type SecretProviderConfigStatus,
type SecretProviderConfigHealthStatus,
type SecretProjectionClass,
type Class3StaticLeaseAllowlistKey,
type SecretScope,
type StorageProvider,
type BillingType,
@@ -399,6 +451,9 @@ export {
type JoinRequestType,
type JoinRequestStatus,
type PermissionKey,
type ConnectionTokenIssuancePath,
type ConnectionTokenIssuanceOutcome,
type ToolAccessActivityAction,
type PluginStatus,
type PluginCategory,
type PluginCapability,
@@ -784,6 +839,8 @@ export type {
RequestConfirmationTarget,
RequestConfirmationPayload,
RequestConfirmationResult,
RequestConfirmationToolActionPayload,
RequestConfirmationToolActionResult,
RequestCheckboxConfirmationOption,
RequestCheckboxConfirmationPayload,
RequestCheckboxConfirmationResult,
@@ -962,6 +1019,131 @@ export type {
SecretStatus,
SecretVersionSelector,
SecretVersionStatus,
ConnectToolAppResult,
ToolOAuthStartResult,
ToolActionRequest,
ToolAccessDecision,
ToolAccessDecisionInput,
ToolAccessReasonCode,
ToolAccessSelector,
ToolPolicyConditions,
ToolAppConnectionActionSummary,
ToolTrustRuleArgumentFilters,
ToolTrustRuleBatchApprovalConfig,
ToolTrustRuleScopeInput,
ToolMcpGateway,
ToolMcpGatewayAuthConfig,
ToolMcpGatewayBearerAuthConfig,
ToolMcpGatewayClientSnippet,
ToolMcpGatewayContextScopeType,
ToolMcpGatewayDefaultProfileMode,
ToolMcpGatewayCallerHeaderPolicy,
ToolMcpGatewayGeneratedMetadataHeaderPolicy,
ToolMcpGatewayHeaderPolicy,
ToolMcpGatewayMetadataPolicy,
ToolMcpGatewayOAuthReservedConfig,
ToolMcpGatewayOnDemandToolsConfig,
ToolMcpGatewayResponseHeaderPolicy,
ToolMcpGatewayStaticHeaderPolicy,
ToolMcpGatewayStatus,
ToolMcpGatewayToken,
ToolMcpGatewayTokenAction,
ToolMcpGatewayTokenCreated,
ToolMcpGatewayTokenSubjectType,
ToolMcpGatewayWithTokens,
FinishToolAppResult,
ToolActionRequestStatus,
ToolApplicationType,
ToolApplicationStatus,
ToolAuditEventType,
ToolAuditOutcome,
ToolCallEvent,
ToolCatalogEntryKind,
ToolConnectionHealthStatus,
ToolConnectionTransport,
ToolConnectionStatus,
ToolConnectionKind,
ToolCatalogEntryStatus,
ToolAppAttentionItem,
ToolAppAttentionReason,
ToolAppsAttentionResponse,
ToolActionRequestListItem,
ToolActionRequestsResponse,
ToolConnectionActivityResponse,
ToolConnectionTestDecision,
ToolConnectionTestToolAccess,
ToolConnectionAccessSummary,
ToolConnectionTestAgent,
ToolConnectionTestAgentsResponse,
ToolConnectionTestCallResult,
ToolConnectionTestCallStatus,
ToolConnectionTestCallStatusPhase,
ToolConnectionLifecycleEvent,
ToolConnectionLifecycleEventType,
ToolConnectionInstall,
ToolConnectionInstallSnapshot,
ToolConnectionInstallTargetType,
ConnectionTokenScope,
ConnectionTokenRequest,
ConnectionTokenAttribution,
ConnectionTokenMintedResponse,
ConnectionTokenUseEnvLeaseResponse,
ConnectionTokenResponse,
ConnectionTokenIssuance,
ToolCredentialSecretRef,
ToolInvocation,
ToolInvocationApprovalState,
ToolInvocationStatus,
ToolPolicy,
ToolPolicyDecision,
ToolPolicyType,
ToolProfile,
ToolProfileBinding,
ToolProfileBindingTargetType,
ToolProfileDefaultAction,
ToolProfileEntry,
ToolProfileEntryEffect,
ToolProfileEntrySelectorType,
ToolProfileEffectiveSummary,
ToolProfileNewToolReviewDecision,
ToolProfileNewToolReviewItem,
ToolProfileNewToolsReview,
ToolProfileNewToolsReviewResult,
ToolProfileSummary,
ToolProfileStatus,
ToolProfileWithDetails,
ToolRateLimitCounter,
ToolRateLimitRule,
ToolRateLimitWindowKind,
ToolRedactedValueSummary,
ToolRiskLevel,
ToolRunDecision,
ToolRunDecisionLookup,
ToolRuntimeKind,
ToolRuntimeHealthSummary,
ToolRuntimeMetricSnapshot,
ToolRuntimeAlertRecommendation,
ToolRuntimeAlertSeverity,
ToolRuntimeAlertStatus,
ToolRuntimeSupportMatrix,
ToolRuntimeSlotStatus,
ToolStdioCommandTemplate,
ToolStdioTemplateToolSummary,
McpConnectionCredentialRef,
ToolApplication,
ToolConnection,
ToolCatalogEntry,
ToolRuntimeSlot,
ToolConnectionHealthCheckResult,
ToolCatalogRefreshResult,
ToolExampleInstallResult,
ToolExampleSmokeCheck,
ToolExampleSmokeResult,
ToolExampleSummary,
McpJsonImportDraft,
McpJsonImportPreview,
CreateToolTrustRuleFromActionRequest,
RevokeToolTrustRule,
Routine,
RoutineEnvConfig,
RoutineManagedByPlugin,
@@ -1108,6 +1290,23 @@ export {
MAX_ISSUE_GRAPH_LIVENESS_AUTO_RECOVERY_LOOKBACK_HOURS,
} from "./types/instance.js";
export type {
SmokeLabServiceStatus,
SmokeRun,
SmokeRunStatus,
SmokeRunStep,
SmokeRunStepPath,
SmokeRunStepStatus,
SmokeRunTrigger,
} from "./types/smoke-lab.js";
export {
SMOKE_RUN_STATUSES,
SMOKE_RUN_STEP_PATHS,
SMOKE_RUN_STEP_STATUSES,
SMOKE_RUN_TRIGGERS,
} from "./types/smoke-lab.js";
export type {
CloudUpstreamConnectStartResponse,
CloudUpstreamActivationDecision,
@@ -1140,6 +1339,13 @@ export {
patchInstanceExperimentalSettingsSchema,
patchInstanceSettingsSchema,
issueGraphLivenessAutoRecoveryRequestSchema,
createSmokeRunSchema,
updateSmokeRunSchema,
recordSmokeRunStepSchema,
smokeRunStatusSchema,
smokeRunStepPathSchema,
smokeRunStepStatusSchema,
smokeRunTriggerSchema,
trustPresetSchema,
lowTrustBoundarySchema,
lowTrustReviewPresetPolicySchema,
@@ -1147,6 +1353,9 @@ export {
type PatchInstanceExperimentalSettings,
type PatchInstanceSettings,
type IssueGraphLivenessAutoRecoveryRequest,
type CreateSmokeRun,
type UpdateSmokeRun,
type RecordSmokeRunStep,
type TrustPresetInput,
type LowTrustBoundaryInput,
type TrustAuthorizationPolicyInput,
@@ -1443,6 +1652,88 @@ export {
rotateSecretSchema,
secretBindingTargetSchema,
updateSecretSchema,
createToolActionRequestSchema,
toolApplicationTypeSchema,
toolApplicationStatusSchema,
toolAuditEventTypeSchema,
toolAuditOutcomeSchema,
toolCatalogEntryKindSchema,
toolCatalogEntryStatusSchema,
toolConnectionHealthStatusSchema,
toolConnectionKindSchema,
toolConnectionTransportSchema,
toolConnectionStatusSchema,
toolCredentialPlacementSchema,
toolCredentialSecretRefSchema,
mcpConnectionCredentialRefSchema,
toolInvocationApprovalStateSchema,
toolInvocationStatusSchema,
toolMcpGatewayAuthConfigSchema,
toolMcpGatewayContextScopeTypeSchema,
toolMcpGatewayDefaultProfileModeSchema,
toolMcpGatewayHeaderPolicySchema,
toolMcpGatewayMetadataPolicySchema,
toolMcpGatewayOnDemandToolsConfigSchema,
toolMcpGatewayStatusSchema,
toolMcpGatewayTokenActionSchema,
toolMcpGatewayTokenSubjectTypeSchema,
toolPolicyDecisionSchema,
toolPolicyTypeSchema,
toolProfileBindingTargetTypeSchema,
toolProfileDefaultActionSchema,
toolProfileEntryEffectSchema,
toolProfileEntrySelectorTypeSchema,
toolProfileStatusSchema,
toolRateLimitWindowKindSchema,
toolRedactedValueSummarySchema,
toolRiskLevelSchema,
toolRuntimeKindSchema,
toolRuntimeSlotStatusSchema,
toolTransportConfigSchema,
toolAccessSelectorSchema,
toolPolicyConditionsSchema,
toolRateLimitRuleSchema,
toolTrustRuleArgumentFiltersSchema,
toolTrustRuleBatchApprovalSchema,
toolTrustRuleScopeSchema,
connectionTokenRequestSchema,
toolConnectionTestCallSchema,
toolPolicyTestRequestSchema,
importMcpJsonSchema,
createToolTrustRuleFromActionRequestSchema,
revokeToolTrustRuleSchema,
connectToolAppSchema,
reconnectToolAppSchema,
createToolApplicationSchema,
finishToolAppSchema,
updateToolApplicationSchema,
createToolConnectionSchema,
createToolMcpGatewaySchema,
createToolMcpGatewayTokenSchema,
createToolStdioCommandTemplateSchema,
disableToolStdioCommandTemplateSchema,
updateToolConnectionSchema,
putToolConnectionInstallsSchema,
updateToolMcpGatewaySchema,
createToolInvocationSchema,
createToolPolicySchema,
createToolProfileBindingForProfileSchema,
createToolProfileBindingSchema,
createToolProfileEntryForProfileSchema,
createToolProfileEntrySchema,
createToolProfileSchema,
createToolProfileWithEntriesSchema,
deleteToolProfileSchema,
duplicateToolPolicySchema,
duplicateToolProfileSchema,
reorderToolPoliciesSchema,
reviewToolProfileNewToolsSchema,
unbindToolProfileBindingSchema,
updateToolPolicySchema,
updateToolProfileEntrySchema,
updateToolProfileSchema,
updateToolProfileWithEntriesSchema,
upsertToolCatalogEntrySchema,
createRoutineSchema,
updateRoutineSchema,
createRoutineTriggerSchema,
@@ -1472,6 +1763,42 @@ export {
type RemoteSecretImportSelection,
type RotateSecret,
type UpdateSecret,
type ConnectToolApp,
type ReconnectToolApp,
type CreateToolActionRequest,
type CreateToolApplication,
type FinishToolApp,
type UpdateToolApplication,
type CreateToolConnection,
type CreateToolMcpGateway,
type CreateToolMcpGatewayToken,
type CreateToolStdioCommandTemplate,
type DisableToolStdioCommandTemplate,
type UpdateToolConnection,
type PutToolConnectionInstalls,
type UpdateToolMcpGateway,
type ConnectionTokenRequestInput,
type ImportMcpJson,
type ToolPolicyTestRequestInput,
type CreateToolInvocation,
type CreateToolPolicy,
type DuplicateToolPolicy,
type CreateToolProfile,
type CreateToolProfileBinding,
type CreateToolProfileBindingForProfile,
type CreateToolProfileEntry,
type CreateToolProfileEntryForProfile,
type CreateToolProfileWithEntries,
type DeleteToolProfile,
type DuplicateToolProfile,
type ReviewToolProfileNewTools,
type ReorderToolPolicies,
type UpdateToolPolicy,
type UpdateToolProfileEntry,
type UpdateToolProfile,
type UpdateToolProfileWithEntries,
type UnbindToolProfileBinding,
type UpsertToolCatalogEntry,
type CreateRoutine,
type UpdateRoutine,
type CreateRoutineTrigger,
@@ -3,6 +3,8 @@ import {
acceptIssueThreadInteractionSchema,
askUserQuestionsResultSchema,
createIssueThreadInteractionSchema,
requestConfirmationPayloadSchema,
requestConfirmationResultSchema,
submitIssueThreadInteractionVerdictsSchema,
} from "./validators/issue.js";
@@ -39,6 +41,49 @@ describe("issue thread interaction schemas", () => {
});
});
it("round-trips versioned tool action payload and lifecycle metadata", () => {
const payload = requestConfirmationPayloadSchema.parse({
version: 1,
prompt: "Approve send_email?",
toolAction: {
version: 1,
actionRequestId: "11111111-1111-4111-8111-111111111111",
invocationId: "22222222-2222-4222-8222-222222222222",
toolName: "send_email",
toolDisplayName: "Send email",
connectionId: "33333333-3333-4333-8333-333333333333",
applicationId: "44444444-4444-4444-8444-444444444444",
appDisplayName: "Gmail",
risk: "write",
previewMarkdown: "Send an email to the reviewed recipient.",
argumentsSummaryJson: '{"to":"recipient@example.com"}',
argumentsHash: "reviewed-arguments-hash",
expiresAt: "2026-07-12T16:00:00.000Z",
},
});
const result = requestConfirmationResultSchema.parse({
version: 1,
outcome: "accepted",
toolAction: {
version: 1,
status: "executed",
errorCode: null,
errorMessage: null,
updatedAt: "2026-07-12T15:05:00.000Z",
},
});
expect(payload.toolAction).toMatchObject({
version: 1,
toolDisplayName: "Send email",
risk: "write",
argumentsHash: "reviewed-arguments-hash",
});
expect(result.toolAction).toMatchObject({ version: 1, status: "executed" });
expect(requestConfirmationPayloadSchema.parse({ version: 1, prompt: "Legacy confirmation?" }).toolAction)
.toBeUndefined();
});
it("accepts issue document targets for request_confirmation interactions", () => {
const parsed = createIssueThreadInteractionSchema.parse({
kind: "request_confirmation",
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import {
getToolAppGalleryEntryForUrl,
TOOL_APP_GALLERY,
} from "./tool-app-gallery.js";
describe("tool app gallery URL matching", () => {
it("matches pasted links against gallery URL patterns", () => {
expect(getToolAppGalleryEntryForUrl("https://mcp.zapier.com/api/mcp")?.key).toBe("zapier");
expect(getToolAppGalleryEntryForUrl("https://api.githubcopilot.com/mcp/")?.key).toBe("github");
expect(getToolAppGalleryEntryForUrl("https://docs.google.com/spreadsheets/d/sheet_123/edit")?.key).toBe("google-sheets");
});
it("returns null for invalid or unknown links", () => {
expect(getToolAppGalleryEntryForUrl("not a url")).toBeNull();
expect(getToolAppGalleryEntryForUrl("https://example.com/mcp")).toBeNull();
expect(getToolAppGalleryEntryForUrl("https://docs.googleapis.com/drive/v3/files")).toBeNull();
});
it("does not list Google Drive until its OAuth client flow is supported", () => {
expect(TOOL_APP_GALLERY.map((entry) => entry.key)).not.toContain("google-drive");
expect(getToolAppGalleryEntryForUrl("https://mcp.google.com/drive")).toBeNull();
});
it("keeps every gallery entry reachable through at least one pattern", () => {
for (const entry of TOOL_APP_GALLERY) {
const example = entry.urlPatterns[0]?.replace("*", "example");
expect(example, `${entry.key} has a pattern`).toBeTruthy();
expect(getToolAppGalleryEntryForUrl(example!)?.key).toBe(entry.key);
}
});
});
+243
View File
@@ -0,0 +1,243 @@
import type { ToolConnectionTransport } from "./types/tool-access.js";
export type AppGalleryAuthKind = "oauth" | "api_key" | "none";
export interface AppGalleryCredentialField {
label: string;
configPath: string;
helpUrl: string;
required?: boolean;
placement?: "header" | "env";
key?: string;
prefix?: string | null;
}
export type AppGalleryTransportTemplate =
| {
transport: Extract<ToolConnectionTransport, "remote_http">;
url: string;
}
| {
transport: Extract<ToolConnectionTransport, "local_stdio">;
templateKey: string;
};
export interface AppGalleryEntry {
key: string;
name: string;
logoUrl: string;
tagline: string;
description?: string;
authKind: AppGalleryAuthKind;
transportTemplate: AppGalleryTransportTemplate;
credentialFields: AppGalleryCredentialField[];
recommendedDefaults: Record<string, unknown>;
urlPatterns: string[];
availability?: {
available: boolean;
reason?: string | null;
robotEmail?: string | null;
};
oauth?: {
provider: string;
scopes: string[];
tokenUrl?: string | null;
metadataUrl?: string | null;
authorizationUrl?: string | null;
};
}
const favicon = (domain: string) => `https://www.google.com/s2/favicons?domain=${domain}&sz=64`;
export const TOOL_APP_GALLERY = [
{
key: "zapier",
name: "Zapier",
logoUrl: favicon("zapier.com"),
tagline: "Connect Zapier-hosted actions to your Paperclip agents.",
description: "Let agents use Zapier automations across the apps your business already runs. Good for handoffs, lightweight operations, and cross-app updates that should stay visible in Paperclip.",
authKind: "api_key",
transportTemplate: {
transport: "remote_http",
url: "https://mcp.zapier.com/api/mcp",
},
credentialFields: [
{
label: "Zapier MCP token",
configPath: "credentials.authorization",
helpUrl: "https://zapier.com/app/settings/authorizations",
required: true,
placement: "header",
key: "Authorization",
prefix: "Bearer ",
},
],
recommendedDefaults: {
access: "all_agents",
askFirstRiskLevels: ["write", "destructive"],
},
urlPatterns: ["https://mcp.zapier.com/*"],
},
{
key: "github",
name: "GitHub",
logoUrl: favicon("github.com"),
tagline: "Read and manage GitHub issues and pull requests.",
description: "Give agents a governed way to inspect repositories, issues, and pull requests. Useful when engineering work needs GitHub context or small updates without leaving Paperclip.",
authKind: "api_key",
transportTemplate: {
transport: "remote_http",
url: "https://api.githubcopilot.com/mcp/",
},
credentialFields: [
{
label: "GitHub token",
configPath: "credentials.authorization",
helpUrl: "https://github.com/settings/tokens",
required: true,
placement: "header",
key: "Authorization",
prefix: "Bearer ",
},
],
recommendedDefaults: {
access: "all_agents",
askFirstRiskLevels: ["write", "destructive"],
},
urlPatterns: ["https://api.githubcopilot.com/mcp/*"],
},
{
key: "slack",
name: "Slack",
logoUrl: favicon("slack.com"),
tagline: "Search channels and coordinate Slack actions.",
description: "Let agents search workspace conversations and coordinate in Slack when work needs team context. Message-sending actions can still ask a human first.",
authKind: "oauth",
transportTemplate: {
transport: "remote_http",
url: "https://mcp.slack.com/mcp",
},
credentialFields: [],
recommendedDefaults: {
access: "all_agents",
askFirstRiskLevels: ["write", "destructive"],
},
urlPatterns: ["https://mcp.slack.com/*"],
oauth: {
provider: "slack",
scopes: ["channels:read", "chat:write", "search:read"],
authorizationUrl: "https://slack.com/oauth/v2/authorize",
tokenUrl: "https://slack.com/api/oauth.v2.access",
},
},
{
key: "notion",
name: "Notion",
logoUrl: favicon("notion.so"),
tagline: "Search and update Notion workspace content.",
description: "Connect Notion so agents can find docs, read project notes, and update workspace pages. Use it for company memory that lives outside Paperclip.",
authKind: "oauth",
transportTemplate: {
transport: "remote_http",
url: "https://mcp.notion.com/mcp",
},
credentialFields: [],
recommendedDefaults: {
access: "all_agents",
askFirstRiskLevels: ["write", "destructive"],
},
urlPatterns: ["https://mcp.notion.com/*"],
oauth: {
provider: "notion",
scopes: ["read_content", "update_content"],
authorizationUrl: "https://api.notion.com/v1/oauth/authorize",
tokenUrl: "https://api.notion.com/v1/oauth/token",
},
},
{
key: "linear",
name: "Linear",
logoUrl: favicon("linear.app"),
tagline: "Read and update Linear issues from agent workflows.",
description: "Let agents look up Linear work and make issue updates when their Paperclip tasks depend on your existing product queue.",
authKind: "oauth",
transportTemplate: {
transport: "remote_http",
url: "https://mcp.linear.app/mcp",
},
credentialFields: [],
recommendedDefaults: {
access: "all_agents",
askFirstRiskLevels: ["write", "destructive"],
},
urlPatterns: ["https://mcp.linear.app/*"],
oauth: {
provider: "linear",
scopes: ["read", "write"],
authorizationUrl: "https://linear.app/oauth/authorize",
tokenUrl: "https://api.linear.app/oauth/token",
},
},
{
key: "google-sheets",
name: "Google Sheets",
logoUrl: favicon("sheets.google.com"),
tagline: "Read and update selected spreadsheets.",
description: "Let agents read and update only the spreadsheets you choose. Share each sheet with the robot email, then paste the sheet links here.",
authKind: "none",
transportTemplate: {
transport: "local_stdio",
templateKey: "paperclip.google-sheets",
},
credentialFields: [],
recommendedDefaults: {
access: "all_agents",
askFirstRiskLevels: ["write", "destructive"],
},
urlPatterns: ["https://docs.google.com/spreadsheets/*", "https://sheets.google.com/*"],
},
{
key: "context7",
name: "Context7",
logoUrl: favicon("context7.com"),
tagline: "Fetch up-to-date library documentation with Context7.",
description: "Let agents pull current library documentation while they work. It is a low-risk reference app for coding and research tasks.",
authKind: "none",
transportTemplate: {
transport: "remote_http",
url: "https://mcp.context7.com/mcp",
},
credentialFields: [],
recommendedDefaults: {
access: "all_agents",
askFirstRiskLevels: [],
},
urlPatterns: ["https://mcp.context7.com/*"],
},
] satisfies AppGalleryEntry[];
export type AppGalleryKey = (typeof TOOL_APP_GALLERY)[number]["key"];
export function getToolAppGalleryEntry(key: string): AppGalleryEntry | null {
return TOOL_APP_GALLERY.find((entry) => entry.key === key) ?? null;
}
function wildcardPatternToRegExp(pattern: string): RegExp {
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
return new RegExp(`^${escaped}$`, "i");
}
export function getToolAppGalleryEntryForUrl(
link: string,
entries: readonly AppGalleryEntry[] = TOOL_APP_GALLERY,
): AppGalleryEntry | null {
let normalized: string;
try {
normalized = new URL(link.trim()).toString();
} catch {
return null;
}
return entries.find((entry) =>
entry.urlPatterns.some((pattern) => wildcardPatternToRegExp(pattern).test(normalized))
) ?? null;
}
+144
View File
@@ -48,6 +48,21 @@ export type {
IssueGraphLivenessAutoRecoveryPreview,
IssueGraphLivenessAutoRecoveryPreviewItem,
} from "./instance.js";
export type {
SmokeLabServiceStatus,
SmokeRun,
SmokeRunStatus,
SmokeRunStep,
SmokeRunStepPath,
SmokeRunStepStatus,
SmokeRunTrigger,
} from "./smoke-lab.js";
export {
SMOKE_RUN_STATUSES,
SMOKE_RUN_STEP_PATHS,
SMOKE_RUN_STEP_STATUSES,
SMOKE_RUN_TRIGGERS,
} from "./smoke-lab.js";
export {
DAILY_RETENTION_PRESETS,
WEEKLY_RETENTION_PRESETS,
@@ -304,6 +319,133 @@ export type {
WorkspaceFileWorkspaceKind,
ResolvedWorkspaceResource,
} from "./workspace-file-resource.js";
export type {
ToolActionRequest,
ToolAccessDecision,
ToolAccessDecisionInput,
ToolAccessReasonCode,
ToolAccessSelector,
ConnectToolAppResult,
FinishToolAppResult,
ToolOAuthStartResult,
ToolTrustRuleArgumentFilters,
ToolTrustRuleBatchApprovalConfig,
ToolTrustRuleScopeInput,
ToolActionRequestStatus,
ToolApplication,
ToolApplicationStatus,
ToolApplicationType,
ToolAuditEventType,
ToolAuditOutcome,
ToolCallEvent,
ToolCatalogEntry,
ToolCatalogEntryKind,
ToolCatalogEntryStatus,
ToolAppAttentionItem,
ToolAppAttentionReason,
ToolAppsAttentionResponse,
ToolActionRequestListItem,
ToolActionRequestsResponse,
ToolConnectionActivityResponse,
ToolConnectionLifecycleEvent,
ToolConnectionLifecycleEventType,
ToolConnectionInstall,
ToolConnectionInstallSnapshot,
ToolConnectionInstallTargetType,
ConnectionTokenAttribution,
ConnectionTokenIssuance,
ConnectionTokenMintedResponse,
ConnectionTokenRequest,
ConnectionTokenResponse,
ConnectionTokenScope,
ConnectionTokenUseEnvLeaseResponse,
ToolConnection,
ToolConnectionHealthStatus,
ToolConnectionTransport,
ToolConnectionStatus,
ToolConnectionKind,
ToolCredentialSecretRef,
ToolInvocation,
ToolInvocationApprovalState,
ToolInvocationStatus,
ToolPolicy,
ToolPolicyConditions,
ToolPolicyDecision,
ToolPolicyType,
ToolMcpGateway,
ToolMcpGatewayAuthConfig,
ToolMcpGatewayBearerAuthConfig,
ToolMcpGatewayClientSnippet,
ToolMcpGatewayContextScopeType,
ToolMcpGatewayDefaultProfileMode,
ToolMcpGatewayCallerHeaderPolicy,
ToolMcpGatewayGeneratedMetadataHeaderPolicy,
ToolMcpGatewayHeaderPolicy,
ToolMcpGatewayMetadataPolicy,
ToolMcpGatewayOAuthReservedConfig,
ToolMcpGatewayOnDemandToolsConfig,
ToolMcpGatewayResponseHeaderPolicy,
ToolMcpGatewayStaticHeaderPolicy,
ToolMcpGatewayStatus,
ToolMcpGatewayToken,
ToolMcpGatewayTokenAction,
ToolMcpGatewayTokenCreated,
ToolMcpGatewayTokenSubjectType,
ToolMcpGatewayWithTokens,
ToolProfile,
ToolProfileBinding,
ToolProfileBindingTargetType,
ToolProfileDefaultAction,
ToolProfileEntry,
ToolProfileEntryEffect,
ToolProfileEntrySelectorType,
ToolProfileEffectiveSummary,
ToolProfileNewToolReviewDecision,
ToolProfileNewToolReviewItem,
ToolProfileNewToolsReview,
ToolProfileNewToolsReviewResult,
ToolProfileSummary,
ToolProfileStatus,
ToolProfileWithDetails,
ToolRateLimitCounter,
ToolRateLimitRule,
ToolRateLimitWindowKind,
ToolRedactedValueSummary,
ToolRiskLevel,
ToolRunDecision,
ToolRunDecisionLookup,
ToolRuntimeKind,
ToolRuntimeHealthSummary,
ToolRuntimeMetricSnapshot,
ToolRuntimeAlertRecommendation,
ToolRuntimeAlertSeverity,
ToolRuntimeAlertStatus,
ToolRuntimeSupportMatrix,
ToolRuntimeSlot,
ToolRuntimeSlotStatus,
ToolStdioCommandTemplate,
ToolStdioTemplateToolSummary,
ToolAppConnectionActionSummary,
McpConnectionCredentialRef,
ToolConnectionHealthCheckResult,
ToolCatalogRefreshResult,
ToolExampleInstallResult,
ToolExampleSmokeCheck,
ToolExampleSmokeResult,
ToolExampleSummary,
McpJsonImportDraft,
McpJsonImportPreview,
CreateToolTrustRuleFromActionRequest,
RevokeToolTrustRule,
ToolConnectionTestDecision,
ToolConnectionTestToolAccess,
ToolConnectionAccessSummary,
ToolConnectionTestAgent,
ToolConnectionTestAgentsResponse,
ToolConnectionTestCallResult,
ToolConnectionTestCallStatus,
ToolConnectionTestCallStatusPhase,
} from "./tool-access.js";
export type {
IssueWorkProduct,
IssueWorkProductType,
@@ -411,6 +553,8 @@ export type {
RequestConfirmationTarget,
RequestConfirmationPayload,
RequestConfirmationResult,
RequestConfirmationToolActionPayload,
RequestConfirmationToolActionResult,
RequestCheckboxConfirmationOption,
RequestCheckboxConfirmationPayload,
RequestCheckboxConfirmationResult,
+2
View File
@@ -48,6 +48,7 @@ export interface InstanceExperimentalSettings {
enableEnvironments: boolean;
enableIsolatedWorkspaces: boolean;
enableStreamlinedLeftNavigation: boolean;
enableApps: boolean;
enablePipelines: boolean;
enableCases: boolean;
enableConferenceRoomChat: boolean;
@@ -56,6 +57,7 @@ export interface InstanceExperimentalSettings {
enableExperimentalFileViewer: boolean;
enableCloudSync: boolean;
enableExternalObjects: boolean;
enableSmokeLab: boolean;
enableBuiltInAgents: boolean;
enableDecisions: boolean;
enableGoalsSidebarLink: boolean;
+39
View File
@@ -1044,6 +1044,43 @@ export type RequestConfirmationTarget =
| RequestConfirmationIssueDocumentTarget
| RequestConfirmationCustomTarget;
/**
* Enrichment block carried on a `request_confirmation` interaction when it gates
* a write/destructive MCP tool call (PAP-13726 §D1). Its presence flips the feed
* card into the dedicated tool-approval rendering (PAP-13745). Arguments are
* redacted server-side before this reaches the client.
*/
export interface RequestConfirmationToolActionPayload {
version: 1;
actionRequestId: string;
invocationId: string;
toolName: string;
toolDisplayName: string;
connectionId: string | null;
applicationId: string | null;
appDisplayName: string | null;
risk: "write" | "destructive";
previewMarkdown: string;
argumentsSummaryJson: string;
argumentsHash: string;
expiresAt: string;
}
/**
* Lifecycle status written back onto the resolved interaction once the operator
* approves. `approve = run`, so the terminal states are executed/failed/expired —
* never a bare "accepted".
*/
export interface RequestConfirmationToolActionResult {
version: 1;
status: "approved" | "executing" | "executed" | "failed" | "expired";
errorCode?: string | null;
errorMessage?: string | null;
resultSummary?: string | null;
resultHref?: string | null;
updatedAt: string;
}
export interface RequestConfirmationPayload {
version: 1;
prompt: string;
@@ -1056,6 +1093,7 @@ export interface RequestConfirmationPayload {
detailsMarkdown?: string | null;
supersedeOnUserComment?: boolean;
target?: RequestConfirmationTarget | null;
toolAction?: RequestConfirmationToolActionPayload;
}
export interface RequestCheckboxConfirmationOption {
@@ -1122,6 +1160,7 @@ export interface RequestConfirmationResult {
recoveryActionId?: string | null;
updatedAt?: string | null;
} | null;
toolAction?: RequestConfirmationToolActionResult;
}
export interface RequestCheckboxConfirmationResult extends RequestConfirmationResult {
+4 -2
View File
@@ -740,15 +740,17 @@ export interface PluginStateRecord {
// ---------------------------------------------------------------------------
/**
* Domain type for a plugin's instance configuration as persisted in the
* Domain type for a plugin's company-scoped configuration as persisted in the
* `plugin_config` table.
* See PLUGIN_SPEC.md §21.3 for the schema definition.
*/
export interface PluginConfig {
/** UUID primary key. */
id: string;
/** FK to `plugins.id`. Unique — each plugin has at most one config row. */
/** FK to `plugins.id`. Unique together with `companyId`. */
pluginId: string;
/** FK to `companies.id`. */
companyId: string;
/** Operator-provided configuration values (validated against `instanceConfigSchema`). */
configJson: Record<string, unknown>;
/** Most recent config validation error, if any. */
+7 -1
View File
@@ -5,6 +5,7 @@ import type {
SecretProvider,
SecretProviderConfigHealthStatus,
SecretProviderConfigStatus,
SecretProjectionClass,
SecretScope,
SecretStatus,
SecretVersionStatus,
@@ -17,6 +18,7 @@ export type {
SecretProvider,
SecretProviderConfigHealthStatus,
SecretProviderConfigStatus,
SecretProjectionClass,
SecretScope,
SecretStatus,
SecretVersionStatus,
@@ -33,6 +35,8 @@ export interface EnvSecretRefBinding {
type: "secret_ref";
secretId: string;
version?: SecretVersionSelector;
projectionClass?: SecretProjectionClass;
projectionAllowlistKey?: string | null;
}
export interface EnvUserSecretRefBinding {
@@ -254,6 +258,8 @@ export interface CompanySecretBinding {
versionSelector: SecretVersionSelector;
required: boolean;
label: string | null;
projectionClass: SecretProjectionClass;
projectionAllowlistKey: string | null;
createdAt: Date;
updatedAt: Date;
}
@@ -284,7 +290,7 @@ export interface SecretAccessEvent {
credentialSubjectId: string | null;
actorType: "agent" | "user" | "system" | "plugin";
actorId: string | null;
consumerType: SecretBindingTargetType;
consumerType: SecretBindingTargetType | "plugin_worker";
consumerId: string;
configPath: string | null;
issueId: string | null;
+46
View File
@@ -0,0 +1,46 @@
export const SMOKE_RUN_TRIGGERS = ["manual", "routine", "ci"] as const;
export type SmokeRunTrigger = (typeof SMOKE_RUN_TRIGGERS)[number];
export const SMOKE_RUN_STATUSES = ["running", "passed", "failed", "cancelled"] as const;
export type SmokeRunStatus = (typeof SMOKE_RUN_STATUSES)[number];
export const SMOKE_RUN_STEP_PATHS = ["P1", "P2", "P3", "P4", "P5", "P6", "P7"] as const;
export type SmokeRunStepPath = (typeof SMOKE_RUN_STEP_PATHS)[number];
export const SMOKE_RUN_STEP_STATUSES = ["pass", "fail", "skipped"] as const;
export type SmokeRunStepStatus = (typeof SMOKE_RUN_STEP_STATUSES)[number];
export interface SmokeRun {
id: string;
companyId: string;
trigger: SmokeRunTrigger;
status: SmokeRunStatus;
startedAt: Date | string;
finishedAt: Date | string | null;
summary: Record<string, unknown>;
createdAt: Date | string;
updatedAt: Date | string;
}
export interface SmokeRunStep {
id: string;
companyId: string;
runId: string;
path: SmokeRunStepPath;
scenarioStep: string;
status: SmokeRunStepStatus;
detail: string | null;
screenshotArtifactRef: Record<string, unknown> | null;
durationMs: number | null;
createdAt: Date | string;
updatedAt: Date | string;
}
export interface SmokeLabServiceStatus {
id: "fake-oauth" | "http-mcp-fixture";
label: string;
status: "stopped" | "running" | "error";
url: string | null;
health: Record<string, unknown> | null;
detail: string | null;
}
File diff suppressed because it is too large. Load diff
+138
View File
@@ -21,6 +21,19 @@ export {
type ResolveBudgetIncident,
} from "./budget.js";
export {
createSmokeRunSchema,
updateSmokeRunSchema,
recordSmokeRunStepSchema,
smokeRunStatusSchema,
smokeRunStepPathSchema,
smokeRunStepStatusSchema,
smokeRunTriggerSchema,
type CreateSmokeRun,
type UpdateSmokeRun,
type RecordSmokeRunStep,
} from "./smoke-lab.js";
export {
createCompanySchema,
updateCompanySchema,
@@ -695,3 +708,128 @@ export {
type SetPluginState,
type ListPluginState,
} from "./plugin.js";
export {
createToolActionRequestSchema,
toolApplicationTypeSchema,
toolApplicationStatusSchema,
toolAuditEventTypeSchema,
toolAuditOutcomeSchema,
toolCatalogEntryKindSchema,
toolCatalogEntryStatusSchema,
toolConnectionHealthStatusSchema,
toolConnectionKindSchema,
toolConnectionStatusSchema,
toolConnectionTransportSchema,
toolCredentialSecretRefSchema,
toolCredentialPlacementSchema,
toolInvocationApprovalStateSchema,
toolInvocationStatusSchema,
toolMcpGatewayAuthConfigSchema,
toolMcpGatewayContextScopeTypeSchema,
toolMcpGatewayDefaultProfileModeSchema,
toolMcpGatewayHeaderPolicySchema,
toolMcpGatewayMetadataPolicySchema,
toolMcpGatewayOnDemandToolsConfigSchema,
toolMcpGatewayStatusSchema,
toolMcpGatewayTokenActionSchema,
toolMcpGatewayTokenSubjectTypeSchema,
toolPolicyDecisionSchema,
toolPolicyTypeSchema,
toolProfileBindingTargetTypeSchema,
toolProfileDefaultActionSchema,
toolProfileEntryEffectSchema,
toolProfileEntrySelectorTypeSchema,
toolProfileStatusSchema,
toolRateLimitWindowKindSchema,
toolRedactedValueSummarySchema,
toolRiskLevelSchema,
toolRuntimeKindSchema,
toolRuntimeSlotStatusSchema,
toolTransportConfigSchema,
toolAccessSelectorSchema,
toolPolicyConditionsSchema,
toolRateLimitRuleSchema,
toolTrustRuleArgumentFiltersSchema,
toolTrustRuleBatchApprovalSchema,
toolTrustRuleScopeSchema,
toolConnectionTestCallSchema,
connectionTokenIssuancePathSchema,
connectionTokenRequestSchema,
connectionTokenScopeSchema,
createToolTrustRuleFromActionRequestSchema,
revokeToolTrustRuleSchema,
toolPolicyTestRequestSchema,
importMcpJsonSchema,
mcpConnectionCredentialRefSchema,
createToolApplicationSchema,
connectToolAppSchema,
reconnectToolAppSchema,
finishToolAppSchema,
updateToolApplicationSchema,
createToolConnectionSchema,
createToolMcpGatewaySchema,
createToolMcpGatewayTokenSchema,
createToolStdioCommandTemplateSchema,
disableToolStdioCommandTemplateSchema,
updateToolConnectionSchema,
putToolConnectionInstallsSchema,
updateToolMcpGatewaySchema,
createToolInvocationSchema,
createToolPolicySchema,
createToolProfileBindingForProfileSchema,
createToolProfileBindingSchema,
createToolProfileEntryForProfileSchema,
createToolProfileEntrySchema,
createToolProfileSchema,
createToolProfileWithEntriesSchema,
deleteToolProfileSchema,
duplicateToolPolicySchema,
duplicateToolProfileSchema,
reorderToolPoliciesSchema,
reviewToolProfileNewToolsSchema,
unbindToolProfileBindingSchema,
updateToolPolicySchema,
updateToolProfileEntrySchema,
updateToolProfileSchema,
updateToolProfileWithEntriesSchema,
upsertToolCatalogEntrySchema,
type CreateToolActionRequest,
type ConnectToolApp,
type ReconnectToolApp,
type CreateToolApplication,
type FinishToolApp,
type UpdateToolApplication,
type CreateToolConnection,
type CreateToolMcpGateway,
type CreateToolMcpGatewayToken,
type CreateToolStdioCommandTemplate,
type DisableToolStdioCommandTemplate,
type UpdateToolConnection,
type PutToolConnectionInstalls,
type UpdateToolMcpGateway,
type CreateToolInvocation,
type CreateToolPolicy,
type CreateToolProfile,
type CreateToolProfileBinding,
type CreateToolProfileBindingForProfile,
type CreateToolProfileEntry,
type CreateToolProfileEntryForProfile,
type CreateToolProfileWithEntries,
type DeleteToolProfile,
type DuplicateToolPolicy,
type DuplicateToolProfile,
type ImportMcpJson,
type ReviewToolProfileNewTools,
type ReorderToolPolicies,
type UpdateToolPolicy,
type UpdateToolProfileEntry,
type UpdateToolProfile,
type UpdateToolProfileWithEntries,
type UnbindToolProfileBinding,
type UpsertToolCatalogEntry,
type ConnectionTokenRequestInput,
type ToolPolicyTestRequestInput,
type CreateToolTrustRuleFromActionRequest,
type RevokeToolTrustRule,
} from "./tool-access.js";
@@ -50,6 +50,12 @@ describe("instance experimental settings validators", () => {
expect(settings.enableBuiltInAgents).toBe(false);
});
it("defaults apps off", () => {
const settings = instanceExperimentalSettingsSchema.parse({});
expect(settings.enableApps).toBe(false);
});
it("accepts worktree run execution patches", () => {
expect(
patchInstanceExperimentalSettingsSchema.parse({
@@ -117,4 +123,14 @@ describe("instance experimental settings validators", () => {
enableBuiltInAgents: true,
});
});
it("accepts apps patches", () => {
expect(
patchInstanceExperimentalSettingsSchema.parse({
enableApps: true,
}),
).toEqual({
enableApps: true,
});
});
});
@@ -42,6 +42,7 @@ export const instanceExperimentalSettingsSchema = z.object({
enableEnvironments: z.boolean().default(false),
enableIsolatedWorkspaces: z.boolean().default(false),
enableStreamlinedLeftNavigation: z.boolean().default(true),
enableApps: z.boolean().default(false),
enablePipelines: z.boolean().default(false),
enableCases: z.boolean().default(false),
enableConferenceRoomChat: z.boolean().default(false),
@@ -50,6 +51,7 @@ export const instanceExperimentalSettingsSchema = z.object({
enableExperimentalFileViewer: z.boolean().default(false),
enableCloudSync: z.boolean().default(false),
enableExternalObjects: z.boolean().default(false),
enableSmokeLab: z.boolean().default(false),
enableBuiltInAgents: z.boolean().default(false),
enableDecisions: z.boolean().default(false),
enableGoalsSidebarLink: z.boolean().default(false),
+31
View File
@@ -742,6 +742,22 @@ export const requestConfirmationTargetSchema = z.discriminatedUnion("type", [
requestConfirmationCustomTargetSchema,
]);
export const requestConfirmationToolActionPayloadSchema = z.object({
version: z.literal(1),
actionRequestId: z.string().uuid(),
invocationId: z.string().uuid(),
toolName: z.string().trim().min(1).max(500),
toolDisplayName: z.string().trim().min(1).max(500),
connectionId: z.string().uuid().nullable(),
applicationId: z.string().uuid().nullable(),
appDisplayName: z.string().trim().min(1).max(500).nullable(),
risk: z.enum(["write", "destructive"]),
previewMarkdown: z.string().trim().min(1).max(20000),
argumentsSummaryJson: z.string().max(20000),
argumentsHash: z.string().trim().min(1).max(255),
expiresAt: z.string().datetime({ offset: true }),
});
export const requestConfirmationPayloadSchema = z.object({
version: z.literal(1),
prompt: z.string().trim().min(1).max(1000),
@@ -754,6 +770,7 @@ export const requestConfirmationPayloadSchema = z.object({
detailsMarkdown: z.string().max(20000).nullable().optional(),
supersedeOnUserComment: z.boolean().optional(),
target: requestConfirmationTargetSchema.nullable().optional(),
toolAction: requestConfirmationToolActionPayloadSchema.optional(),
});
export const requestCheckboxConfirmationOptionSchema = z.object({
@@ -867,6 +884,19 @@ export const requestConfirmationResumeFailureSchema = z.object({
updatedAt: z.string().trim().min(1).nullable().optional(),
});
export const requestConfirmationToolActionResultSchema = z.object({
version: z.literal(1),
status: z.enum(["approved", "executing", "executed", "failed", "expired"]),
errorCode: z.string().trim().min(1).max(120).nullable().optional(),
errorMessage: z.string().trim().min(1).max(4000).nullable().optional(),
// Populated on `executed` so the card can report the outcome (e.g. "Row 42
// added") instead of a bare checkmark, with an optional deep-link when the
// connector returns a URL (PAP-13745 §5 Executed / Peak-End).
resultSummary: z.string().trim().min(1).max(4000).nullable().optional(),
resultHref: z.string().trim().url().max(2000).nullable().optional(),
updatedAt: z.string().datetime({ offset: true }),
});
export const requestConfirmationResultSchema = z.object({
version: z.literal(1),
outcome: z.enum(["accepted", "rejected", "superseded_by_comment", "stale_target"]),
@@ -874,6 +904,7 @@ export const requestConfirmationResultSchema = z.object({
commentId: z.string().uuid().nullable().optional(),
staleTarget: requestConfirmationTargetSchema.nullable().optional(),
resumeFailure: requestConfirmationResumeFailureSchema.nullable().optional(),
toolAction: requestConfirmationToolActionResultSchema.optional(),
});
export const requestCheckboxConfirmationResultSchema = requestConfirmationResultSchema.extend({
+5 -3
View File
@@ -1135,25 +1135,27 @@ export const installPluginSchema = z.object({
export type InstallPlugin = z.infer<typeof installPluginSchema>;
// ---------------------------------------------------------------------------
// Plugin config (instance configuration) schemas
// Plugin config (company-scoped configuration) schemas
// ---------------------------------------------------------------------------
/**
* Schema for creating or updating a plugin's instance configuration.
* Schema for creating or updating a plugin's company-scoped configuration.
* configJson is validated permissively here; runtime validation against
* the plugin's instanceConfigSchema is done at the service layer.
*/
export const upsertPluginConfigSchema = z.object({
companyId: z.string().uuid(),
configJson: z.record(z.string(), z.unknown()),
});
export type UpsertPluginConfig = z.infer<typeof upsertPluginConfigSchema>;
/**
* Schema for partially updating a plugin's instance configuration.
* Schema for partially updating a plugin's company-scoped configuration.
* Allows a partial merge of config values.
*/
export const patchPluginConfigSchema = z.object({
companyId: z.string().uuid(),
configJson: z.record(z.string(), z.unknown()),
});
+5
View File
@@ -2,6 +2,7 @@ import { z } from "zod";
import {
SECRET_BINDING_TARGET_TYPES,
SECRET_MANAGED_MODES,
SECRET_PROJECTION_CLASSES,
SECRET_PROVIDER_CONFIG_STATUSES,
SECRET_PROVIDERS,
SECRET_STATUSES,
@@ -20,6 +21,8 @@ export const envBindingSecretRefSchema = z.object({
type: z.literal("secret_ref"),
secretId: z.string().uuid(),
version: secretVersionSelectorSchema.optional(),
projectionClass: z.enum(SECRET_PROJECTION_CLASSES).optional(),
projectionAllowlistKey: z.string().trim().min(1).max(160).optional().nullable(),
});
export const envBindingUserSecretRefSchema = z.object({
@@ -135,6 +138,8 @@ export const createSecretBindingSchema = secretBindingTargetSchema.extend({
versionSelector: secretVersionSelectorSchema.default("latest"),
required: z.boolean().default(true),
label: z.string().optional().nullable(),
projectionClass: z.enum(SECRET_PROJECTION_CLASSES).optional(),
projectionAllowlistKey: z.string().trim().min(1).max(160).optional().nullable(),
});
export type CreateSecretBinding = z.infer<typeof createSecretBindingSchema>;
@@ -0,0 +1,35 @@
import { z } from "zod";
import {
SMOKE_RUN_STATUSES,
SMOKE_RUN_STEP_PATHS,
SMOKE_RUN_STEP_STATUSES,
SMOKE_RUN_TRIGGERS,
} from "../types/smoke-lab.js";
export const smokeRunTriggerSchema = z.enum(SMOKE_RUN_TRIGGERS);
export const smokeRunStatusSchema = z.enum(SMOKE_RUN_STATUSES);
export const smokeRunStepPathSchema = z.enum(SMOKE_RUN_STEP_PATHS);
export const smokeRunStepStatusSchema = z.enum(SMOKE_RUN_STEP_STATUSES);
export const createSmokeRunSchema = z.object({
trigger: smokeRunTriggerSchema.default("manual"),
summary: z.record(z.string(), z.unknown()).default({}),
}).strict();
export const updateSmokeRunSchema = z.object({
status: smokeRunStatusSchema,
summary: z.record(z.string(), z.unknown()).optional(),
}).strict();
export const recordSmokeRunStepSchema = z.object({
path: smokeRunStepPathSchema,
scenarioStep: z.string().min(1).max(200),
status: smokeRunStepStatusSchema,
detail: z.string().max(4_000).nullable().optional(),
screenshotArtifactRef: z.record(z.string(), z.unknown()).nullable().optional(),
durationMs: z.number().int().min(0).max(24 * 60 * 60 * 1000).nullable().optional(),
}).strict();
export type CreateSmokeRun = z.infer<typeof createSmokeRunSchema>;
export type UpdateSmokeRun = z.infer<typeof updateSmokeRunSchema>;
export type RecordSmokeRunStep = z.infer<typeof recordSmokeRunStepSchema>;
@@ -0,0 +1,50 @@
import { describe, expect, it } from "vitest";
import {
createToolConnectionSchema,
toolRedactedValueSummarySchema,
toolTransportConfigSchema,
} from "./tool-access.js";
describe("tool access validators", () => {
it("rejects raw credential-looking fields in transport config", () => {
const parsed = toolTransportConfigSchema.safeParse({
url: "https://example.test/mcp",
headers: {
Authorization: "Bearer raw-token",
},
});
expect(parsed.success).toBe(false);
if (!parsed.success) {
expect(parsed.error.issues[0]?.message).toContain("credentialSecretRefs");
}
});
it("accepts secret references for connection credentials", () => {
const parsed = createToolConnectionSchema.safeParse({
applicationId: "11111111-1111-4111-8111-111111111111",
name: "GitHub fixture",
connectionKind: "managed",
transportConfig: { url: "https://example.test/mcp" },
credentialSecretRefs: [
{
secretId: "22222222-2222-4222-8222-222222222222",
configPath: "headers.Authorization",
versionSelector: "latest",
},
],
});
expect(parsed.success).toBe(true);
});
it("keeps invocation payload summaries redacted and bounded", () => {
const parsed = toolRedactedValueSummarySchema.parse({
summary: "Redacted arguments: 2 fields omitted.",
sha256: "a".repeat(64),
redactedFields: ["headers.Authorization", "body.token"],
});
expect(parsed.redactedFields).toEqual(["headers.Authorization", "body.token"]);
});
});
@@ -0,0 +1,766 @@
import { z } from "zod";
import {
CONNECTION_TOKEN_ISSUANCE_PATHS,
SECRET_PROJECTION_CLASSES,
TOOL_ACTION_REQUEST_STATUSES,
TOOL_APPLICATION_STATUSES,
TOOL_APPLICATION_TYPES,
TOOL_AUDIT_EVENT_TYPES,
TOOL_AUDIT_OUTCOMES,
TOOL_CATALOG_ENTRY_KINDS,
TOOL_CATALOG_ENTRY_STATUSES,
TOOL_CONNECTION_HEALTH_STATUSES,
TOOL_CONNECTION_KINDS,
TOOL_INVOCATION_APPROVAL_STATES,
TOOL_INVOCATION_STATUSES,
TOOL_MCP_GATEWAY_CONTEXT_SCOPE_TYPES,
TOOL_MCP_GATEWAY_DEFAULT_PROFILE_MODES,
TOOL_MCP_GATEWAY_STATUSES,
TOOL_MCP_GATEWAY_TOKEN_ACTIONS,
TOOL_MCP_GATEWAY_TOKEN_SUBJECT_TYPES,
TOOL_POLICY_DECISIONS,
TOOL_POLICY_TYPES,
TOOL_PROFILE_BINDING_TARGET_TYPES,
TOOL_PROFILE_DEFAULT_ACTIONS,
TOOL_PROFILE_ENTRY_EFFECTS,
TOOL_PROFILE_ENTRY_SELECTOR_TYPES,
TOOL_PROFILE_STATUSES,
TOOL_RATE_LIMIT_WINDOW_KINDS,
TOOL_RISK_LEVELS,
TOOL_RUNTIME_KINDS,
TOOL_RUNTIME_SLOT_STATUSES,
} from "../constants.js";
import { jsonSchemaSchema } from "./plugin.js";
export const toolApplicationTypeSchema = z.enum(TOOL_APPLICATION_TYPES);
export const toolApplicationStatusSchema = z.enum(TOOL_APPLICATION_STATUSES);
export const toolConnectionTransportSchema = z.enum(["remote_http", "local_stdio"]);
export const toolConnectionStatusSchema = z.enum(["draft", "active", "disabled", "archived"]);
export const toolConnectionInstallTargetTypeSchema = z.enum(["company", "agent"]);
export const toolCredentialPlacementSchema = z.enum(["header", "env"]);
export const toolConnectionKindSchema = z.enum(TOOL_CONNECTION_KINDS);
export const toolConnectionHealthStatusSchema = z.enum(TOOL_CONNECTION_HEALTH_STATUSES);
export const toolCatalogEntryKindSchema = z.enum(TOOL_CATALOG_ENTRY_KINDS);
export const toolCatalogEntryStatusSchema = z.enum(TOOL_CATALOG_ENTRY_STATUSES);
export const toolRiskLevelSchema = z.enum(TOOL_RISK_LEVELS);
export const toolProfileStatusSchema = z.enum(TOOL_PROFILE_STATUSES);
export const toolProfileDefaultActionSchema = z.enum(TOOL_PROFILE_DEFAULT_ACTIONS);
export const toolProfileEntrySelectorTypeSchema = z.enum(TOOL_PROFILE_ENTRY_SELECTOR_TYPES);
export const toolProfileEntryEffectSchema = z.enum(TOOL_PROFILE_ENTRY_EFFECTS);
export const toolProfileBindingTargetTypeSchema = z.enum(TOOL_PROFILE_BINDING_TARGET_TYPES);
export const toolPolicyTypeSchema = z.enum(TOOL_POLICY_TYPES);
export const toolPolicyDecisionSchema = z.enum(TOOL_POLICY_DECISIONS);
export const toolInvocationStatusSchema = z.enum(TOOL_INVOCATION_STATUSES);
export const toolInvocationApprovalStateSchema = z.enum(TOOL_INVOCATION_APPROVAL_STATES);
export const toolMcpGatewayStatusSchema = z.enum(TOOL_MCP_GATEWAY_STATUSES);
export const toolMcpGatewayDefaultProfileModeSchema = z.enum(TOOL_MCP_GATEWAY_DEFAULT_PROFILE_MODES);
export const toolMcpGatewayContextScopeTypeSchema = z.enum(TOOL_MCP_GATEWAY_CONTEXT_SCOPE_TYPES);
export const toolMcpGatewayTokenSubjectTypeSchema = z.enum(TOOL_MCP_GATEWAY_TOKEN_SUBJECT_TYPES);
export const toolMcpGatewayTokenActionSchema = z.enum(TOOL_MCP_GATEWAY_TOKEN_ACTIONS);
export const toolActionRequestStatusSchema = z.enum(TOOL_ACTION_REQUEST_STATUSES);
export const toolAuditEventTypeSchema = z.enum(TOOL_AUDIT_EVENT_TYPES);
export const toolAuditOutcomeSchema = z.enum(TOOL_AUDIT_OUTCOMES);
export const toolRuntimeKindSchema = z.enum(TOOL_RUNTIME_KINDS);
export const toolRuntimeSlotStatusSchema = z.enum(TOOL_RUNTIME_SLOT_STATUSES);
export const toolRateLimitWindowKindSchema = z.enum(TOOL_RATE_LIMIT_WINDOW_KINDS);
const safeKeyPattern = /^[a-z0-9][a-z0-9._:-]*$/i;
const sensitiveConfigKeyPattern =
/^(access[-_]?key([-_]?id)?|api[-_]?key|authorization|bearer|client[-_]?secret|credential|credentials|jwt|password|passwd|private[-_]?key|refresh[-_]?token|secret|secret[-_]?access[-_]?key|secret[-_]?key|session[-_]?token|token)$/i;
function rejectSensitiveConfigKeys(value: unknown, ctx: z.RefinementCtx, path: Array<string | number> = []) {
if (!value || typeof value !== "object") return;
if (Array.isArray(value)) {
value.forEach((entry, index) => rejectSensitiveConfigKeys(entry, ctx, [...path, index]));
return;
}
for (const [key, nested] of Object.entries(value)) {
if (sensitiveConfigKeyPattern.test(key)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: [...path, key],
message: `Tool access config cannot persist sensitive field: ${key}. Use credentialSecretRefs instead.`,
});
}
rejectSensitiveConfigKeys(nested, ctx, [...path, key]);
}
}
export const toolCredentialSecretRefSchema = z.object({
secretId: z.string().uuid(),
versionSelector: z.union([z.literal("latest"), z.number().int().positive()]).optional(),
configPath: z.string().trim().min(1).max(200),
required: z.boolean().optional(),
label: z.string().trim().max(120).optional().nullable(),
projectionClass: z.enum(SECRET_PROJECTION_CLASSES).optional(),
projectionAllowlistKey: z.string().trim().min(1).max(160).optional().nullable(),
});
export const mcpConnectionCredentialRefSchema = z.object({
name: z.string().trim().min(1).max(120),
secretId: z.string().uuid(),
version: z.union([z.literal("latest"), z.number().int().positive()]).optional(),
placement: toolCredentialPlacementSchema,
key: z.string().trim().min(1).max(160),
prefix: z.string().max(120).nullable().optional(),
});
export const toolTransportConfigSchema = z.record(z.string(), z.unknown()).superRefine(rejectSensitiveConfigKeys);
export const toolRedactedValueSummarySchema = z.object({
summary: z.string().max(4000),
sizeBytes: z.number().int().min(0).optional().nullable(),
sha256: z.string().trim().regex(/^[a-f0-9]{64}$/i).optional().nullable(),
redactedFields: z.array(z.string().trim().min(1).max(200)).default([]).optional(),
artifactId: z.string().uuid().optional().nullable(),
});
export const createToolApplicationSchema = z.object({
applicationKey: z.string().trim().min(1).max(160).regex(safeKeyPattern).optional(),
name: z.string().trim().min(1).max(160),
description: z.string().max(4000).optional().nullable(),
type: toolApplicationTypeSchema,
status: toolApplicationStatusSchema.optional(),
pluginId: z.string().uuid().optional().nullable(),
ownerAgentId: z.string().uuid().optional().nullable(),
ownerUserId: z.string().optional().nullable(),
metadata: z.record(z.string(), z.unknown()).optional().nullable(),
});
export type CreateToolApplication = z.infer<typeof createToolApplicationSchema>;
export const updateToolApplicationSchema = createToolApplicationSchema.partial().refine(
(value) => Object.keys(value).length > 0,
{ message: "At least one tool application field is required" },
);
export type UpdateToolApplication = z.infer<typeof updateToolApplicationSchema>;
export const createToolConnectionSchema = z.object({
applicationId: z.string().uuid().optional(),
applicationName: z.string().trim().min(1).max(160).optional(),
name: z.string().trim().min(1).max(160),
transport: toolConnectionTransportSchema.optional(),
status: toolConnectionStatusSchema.optional(),
connectionKind: toolConnectionKindSchema.default("managed"),
config: toolTransportConfigSchema.optional(),
transportConfig: toolTransportConfigSchema.default({}),
credentialRefs: z.array(mcpConnectionCredentialRefSchema).optional(),
credentialSecretRefs: z.array(toolCredentialSecretRefSchema).default([]),
enabled: z.boolean().optional(),
});
export type CreateToolConnection = z.infer<typeof createToolConnectionSchema>;
export const updateToolConnectionSchema = createToolConnectionSchema.omit({ applicationId: true }).partial().refine(
(value) => Object.keys(value).length > 0,
{ message: "At least one tool connection field is required" },
);
export type UpdateToolConnection = z.infer<typeof updateToolConnectionSchema>;
export const putToolConnectionInstallsSchema = z.object({
installs: z.array(z.object({
targetType: toolConnectionInstallTargetTypeSchema,
targetId: z.string().trim().min(1).max(200),
})).max(1000),
}).strict();
export type PutToolConnectionInstalls = z.infer<typeof putToolConnectionInstallsSchema>;
export const connectionTokenIssuancePathSchema = z.enum(CONNECTION_TOKEN_ISSUANCE_PATHS);
export const connectionTokenScopeSchema = z.union([
z.string().trim().min(1).max(500),
z.array(z.string().trim().min(1).max(240)).max(100),
]);
export const connectionTokenRequestSchema = z.object({
scope: connectionTokenScopeSchema.optional(),
requestedTtlSeconds: z.number().int().positive().max(86_400).optional(),
}).strict();
export type ConnectionTokenRequestInput = z.infer<typeof connectionTokenRequestSchema>;
const envKeyPattern = /^[A-Z_][A-Z0-9_]*$/i;
export const toolStdioTemplateToolSchema = z.object({
name: z.string().trim().min(1).max(240),
title: z.string().trim().max(240).optional().nullable(),
description: z.string().max(8000).optional().nullable(),
inputSchema: jsonSchemaSchema.optional().nullable(),
annotations: z.record(z.string(), z.unknown()).optional().nullable(),
});
export const createToolStdioCommandTemplateSchema = z.object({
templateId: z.string().trim().min(1).max(160).regex(safeKeyPattern),
name: z.string().trim().min(1).max(160),
description: z.string().max(4000).optional().nullable(),
command: z.string().trim().min(1).max(2000),
args: z.array(z.string().max(2000)).max(100).default([]),
envKeys: z.array(z.string().trim().min(1).max(160).regex(envKeyPattern)).max(200).default([]),
tools: z.array(toolStdioTemplateToolSchema).max(500).default([]),
});
export type CreateToolStdioCommandTemplate = z.infer<typeof createToolStdioCommandTemplateSchema>;
export const disableToolStdioCommandTemplateSchema = z.object({
reason: z.string().trim().max(1000).optional().nullable(),
});
export type DisableToolStdioCommandTemplate = z.infer<typeof disableToolStdioCommandTemplateSchema>;
export const connectToolAppSchema = z.object({
galleryKey: z.string().trim().min(1).max(120).optional(),
link: z.string().trim().url().max(2000).optional(),
name: z.string().trim().min(1).max(160).optional(),
credentialValues: z.record(z.string().trim().min(1).max(200), z.string().min(1)).optional(),
configValues: z.record(z.string().trim().min(1).max(200), z.unknown()).optional(),
applicationId: z.string().uuid().optional(),
}).refine(
(value) => Boolean(value.galleryKey) !== Boolean(value.link),
{ message: "Provide exactly one of galleryKey or link" },
);
export type ConnectToolApp = z.infer<typeof connectToolAppSchema>;
export const reconnectToolAppSchema = z.object({
credentialValues: z.record(z.string().trim().min(1).max(200), z.string().min(1)),
});
export type ReconnectToolApp = z.infer<typeof reconnectToolAppSchema>;
export const finishToolAppSchema = z.object({
enabledCatalogEntryIds: z.array(z.string().uuid()).max(500).default([]),
askFirstCatalogEntryIds: z.array(z.string().uuid()).max(500).default([]),
access: z.union([
z.literal("all_agents"),
z.object({ agentIds: z.array(z.string().uuid()).min(1).max(250) }),
]),
});
export type FinishToolApp = z.infer<typeof finishToolAppSchema>;
export const upsertToolCatalogEntrySchema = z.object({
applicationId: z.string().uuid(),
connectionId: z.string().uuid(),
entryKind: toolCatalogEntryKindSchema.default("tool"),
toolName: z.string().trim().min(1).max(240),
title: z.string().trim().max(240).optional().nullable(),
description: z.string().max(8000).optional().nullable(),
inputSchema: jsonSchemaSchema.optional().nullable(),
outputSchema: jsonSchemaSchema.optional().nullable(),
annotations: z.record(z.string(), z.unknown()).optional().nullable(),
riskLevel: toolRiskLevelSchema.default("medium"),
isReadOnly: z.boolean().default(false),
isWrite: z.boolean().default(false),
isDestructive: z.boolean().default(false),
status: toolCatalogEntryStatusSchema.default("active"),
version: z.string().trim().max(200).optional().nullable(),
schemaHash: z.string().trim().max(128).optional().nullable(),
});
export type UpsertToolCatalogEntry = z.infer<typeof upsertToolCatalogEntrySchema>;
export const createToolProfileSchema = z.object({
profileKey: z.string().trim().min(1).max(160).regex(safeKeyPattern),
name: z.string().trim().min(1).max(160),
description: z.string().max(4000).optional().nullable(),
status: toolProfileStatusSchema.default("active"),
defaultAction: toolProfileDefaultActionSchema.default("deny"),
metadata: z.record(z.string(), z.unknown()).optional().nullable(),
});
export type CreateToolProfile = z.infer<typeof createToolProfileSchema>;
export const updateToolProfileSchema = createToolProfileSchema.partial().refine(
(value) => Object.keys(value).length > 0,
{ message: "At least one tool profile field is required" },
);
export type UpdateToolProfile = z.infer<typeof updateToolProfileSchema>;
export const createToolProfileEntrySchema = z.object({
profileId: z.string().uuid(),
selectorType: toolProfileEntrySelectorTypeSchema,
effect: toolProfileEntryEffectSchema.default("include"),
applicationId: z.string().uuid().optional().nullable(),
connectionId: z.string().uuid().optional().nullable(),
catalogEntryId: z.string().uuid().optional().nullable(),
toolName: z.string().trim().min(1).max(240).optional().nullable(),
riskLevel: toolRiskLevelSchema.optional().nullable(),
conditions: z.record(z.string(), z.unknown()).optional().nullable(),
});
export type CreateToolProfileEntry = z.infer<typeof createToolProfileEntrySchema>;
export const createToolProfileEntryForProfileSchema = createToolProfileEntrySchema.omit({ profileId: true });
export type CreateToolProfileEntryForProfile = z.infer<typeof createToolProfileEntryForProfileSchema>;
export const updateToolProfileEntrySchema = createToolProfileEntryForProfileSchema.partial().refine(
(value) => Object.keys(value).length > 0,
{ message: "At least one tool profile entry field is required" },
);
export type UpdateToolProfileEntry = z.infer<typeof updateToolProfileEntrySchema>;
export const createToolProfileWithEntriesSchema = createToolProfileSchema.extend({
entries: z.array(createToolProfileEntryForProfileSchema).max(250).optional(),
});
export type CreateToolProfileWithEntries = z.infer<typeof createToolProfileWithEntriesSchema>;
export const duplicateToolProfileSchema = z.object({
name: z.string().trim().min(1).max(160),
includeAssignments: z.boolean().default(false),
});
export type DuplicateToolProfile = z.infer<typeof duplicateToolProfileSchema>;
export const updateToolProfileWithEntriesSchema = createToolProfileSchema.partial().extend({
entries: z.array(createToolProfileEntryForProfileSchema).max(250).optional(),
}).refine(
(value) => Object.keys(value).length > 0,
{ message: "At least one tool profile field is required" },
);
export type UpdateToolProfileWithEntries = z.infer<typeof updateToolProfileWithEntriesSchema>;
export const reviewToolProfileNewToolsSchema = z.object({
decisions: z.array(z.object({
catalogEntryId: z.string().uuid(),
decision: z.enum(["allow", "keep_blocked"]),
})).min(1).max(250),
});
export type ReviewToolProfileNewTools = z.infer<typeof reviewToolProfileNewToolsSchema>;
export const deleteToolProfileSchema = z.object({
force: z.boolean().default(false),
reassignToProfileId: z.string().uuid().optional(),
}).default({});
export type DeleteToolProfile = z.infer<typeof deleteToolProfileSchema>;
export const createToolProfileBindingSchema = z.object({
profileId: z.string().uuid(),
targetType: toolProfileBindingTargetTypeSchema,
targetId: z.string().trim().min(1).max(200),
priority: z.number().int().min(0).max(10000).default(100),
metadata: z.record(z.string(), z.unknown()).optional().nullable(),
});
export type CreateToolProfileBinding = z.infer<typeof createToolProfileBindingSchema>;
export const createToolProfileBindingForProfileSchema = createToolProfileBindingSchema.omit({ profileId: true });
export type CreateToolProfileBindingForProfile = z.infer<typeof createToolProfileBindingForProfileSchema>;
export const unbindToolProfileBindingSchema = createToolProfileBindingForProfileSchema.pick({
targetType: true,
targetId: true,
});
export type UnbindToolProfileBinding = z.infer<typeof unbindToolProfileBindingSchema>;
const headerNameSchema = z.string().trim().min(1).max(120).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/);
export const toolMcpGatewayAuthConfigSchema = z.object({
version: z.literal(1).default(1),
bearer: z.object({
enabled: z.boolean().default(true),
tokenPrefix: z.literal("pcgw").default("pcgw"),
defaultTtlSeconds: z.number().int().positive().max(31_536_000).nullable().default(7_776_000),
requireFiniteExpiry: z.boolean().default(true),
longLivedTokenRequiresOverride: z.boolean().default(true),
}).default({}),
oauth: z.object({
enabled: z.literal(false).default(false),
reservedFor: z.literal("v1_5").default("v1_5"),
protectedResourceMetadataPath: z.string().trim().max(240).optional().nullable(),
dynamicClientRegistration: z.literal(false).optional(),
authorizationCodePkce: z.literal(false).optional(),
}).default({}),
});
export const toolMcpGatewayHeaderPolicySchema = z.object({
version: z.literal(1).default(1),
callerPassthrough: z.object({
enabled: z.boolean().default(false),
allowedHeaders: z.array(headerNameSchema).max(50).default([]),
}).default({}),
staticHeaders: z.array(z.object({
name: headerNameSchema,
valueRef: z.string().trim().max(240).optional().nullable(),
value: z.string().max(4000).optional().nullable(),
})).max(50).default([]),
generatedMetadata: z.object({
enabled: z.boolean().default(false),
allowedHeaders: z.array(headerNameSchema).max(20).default([]),
}).default({}),
responseHeaders: z.object({
forwardMcpRequiredHeaders: z.boolean().default(true),
forwardSafeCacheHeaders: z.boolean().default(true),
}).default({}),
});
export const toolMcpGatewayMetadataPolicySchema = z.object({
version: z.literal(1).default(1),
forwardCompanyId: z.boolean().default(false),
forwardGatewayId: z.boolean().default(false),
forwardProjectId: z.boolean().default(false),
forwardIssueId: z.boolean().default(false),
forwardAgentId: z.boolean().default(false),
forwardRunId: z.boolean().default(false),
forwardCorrelationId: z.boolean().default(true),
});
export const toolMcpGatewayOnDemandToolsConfigSchema = z.object({
enabled: z.boolean().default(false),
searchToolName: z.literal("search_tools").default("search_tools"),
runToolName: z.literal("run_tool").default("run_tool"),
});
export const createToolMcpGatewaySchema = z.object({
name: z.string().trim().min(1).max(160),
slug: z.string().trim().min(1).max(120).regex(safeKeyPattern).optional(),
displaySlug: z.string().trim().min(1).max(120).regex(safeKeyPattern).optional(),
description: z.string().max(4000).optional().nullable(),
profileId: z.string().uuid(),
defaultProfileMode: toolMcpGatewayDefaultProfileModeSchema.default("gateway_only").optional(),
contextScopeType: toolMcpGatewayContextScopeTypeSchema.default("none").optional(),
contextScopeId: z.string().trim().min(1).max(200).optional().nullable(),
agentId: z.string().uuid().optional().nullable(),
projectId: z.string().uuid().optional().nullable(),
issueId: z.string().uuid().optional().nullable(),
approvalIssueId: z.string().uuid().optional().nullable(),
authConfig: toolMcpGatewayAuthConfigSchema.optional(),
headerPolicy: toolMcpGatewayHeaderPolicySchema.optional(),
metadataPolicy: toolMcpGatewayMetadataPolicySchema.optional(),
onDemandToolsConfig: toolMcpGatewayOnDemandToolsConfigSchema.optional(),
metadata: z.record(z.string(), z.unknown()).optional().nullable(),
});
export type CreateToolMcpGateway = z.infer<typeof createToolMcpGatewaySchema>;
export const updateToolMcpGatewaySchema = createToolMcpGatewaySchema
.partial()
.extend({ status: toolMcpGatewayStatusSchema.optional() })
.refine((value) => Object.keys(value).length > 0, { message: "At least one gateway field is required" });
export type UpdateToolMcpGateway = z.infer<typeof updateToolMcpGatewaySchema>;
export const createToolMcpGatewayTokenSchema = z.object({
name: z.string().trim().min(1).max(160),
subjectType: toolMcpGatewayTokenSubjectTypeSchema.default("gateway_client").optional(),
subjectId: z.string().trim().min(1).max(240).optional().nullable(),
clientLabel: z.string().trim().min(1).max(160),
ownerNote: z.string().trim().min(1).max(1000),
allowedActions: z.array(toolMcpGatewayTokenActionSchema).min(1).max(TOOL_MCP_GATEWAY_TOKEN_ACTIONS.length).default(["tools/list", "tools/call"]).optional(),
expiresAt: z.coerce.date().optional().nullable(),
expiryOverrideReason: z.string().trim().min(1).max(1000).optional().nullable(),
}).superRefine((value, ctx) => {
if (value.subjectType && value.subjectType !== "gateway_client") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["subjectType"],
message: "Public V1 token minting only supports gateway_client subjects; heartbeat_run is runtime-managed, while board_user and agent are reserved for later OAuth/user-bound flows.",
});
}
if (value.expiresAt === null && !value.expiryOverrideReason) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["expiryOverrideReason"],
message: "Non-expiring gateway tokens require an override reason.",
});
}
});
export type CreateToolMcpGatewayToken = z.infer<typeof createToolMcpGatewayTokenSchema>;
const argumentConditionSchema = z.object({
fieldEquals: z.record(z.string().trim().min(1).max(120), z.unknown()).optional(),
fieldNotEquals: z.record(z.string().trim().min(1).max(120), z.unknown()).optional(),
fieldIn: z.record(z.string().trim().min(1).max(120), z.array(z.unknown()).min(1).max(100)).optional(),
fieldMatches: z.record(z.string().trim().min(1).max(120), z.string().trim().min(1).max(500)).optional(),
fieldExists: z.array(z.string().trim().min(1).max(120)).max(100).optional(),
fieldAbsent: z.array(z.string().trim().min(1).max(120)).max(100).optional(),
}).strict().refine(
(value) => Object.values(value).some((nested) => Array.isArray(nested) ? nested.length > 0 : Boolean(nested && Object.keys(nested).length > 0)),
{ message: "Argument conditions must include at least one field predicate" },
);
const timeWindowConditionSchema = z.object({
startAt: z.string().trim().datetime({ offset: true }).optional(),
endAt: z.string().trim().datetime({ offset: true }).optional(),
daysOfWeekUtc: z.array(z.number().int().min(0).max(6)).max(7).optional(),
startHourUtc: z.number().int().min(0).max(23).optional(),
endHourUtc: z.number().int().min(0).max(24).optional(),
}).strict().refine(
(value) => value.startAt || value.endAt || value.daysOfWeekUtc?.length || value.startHourUtc !== undefined || value.endHourUtc !== undefined,
{ message: "timeWindow must include at least one bound" },
);
const actorConditionSchema = z.object({
actorType: z.enum(["agent", "user", "system", "plugin"]).optional(),
actorTypes: z.array(z.enum(["agent", "user", "system", "plugin"])).max(20).optional(),
agentId: z.string().uuid().optional(),
agentIds: z.array(z.string().uuid()).max(100).optional(),
}).strict();
const contextConditionSchema = z.object({
projectId: z.string().uuid().optional(),
projectIds: z.array(z.string().uuid()).max(100).optional(),
routineId: z.string().uuid().optional(),
routineIds: z.array(z.string().uuid()).max(100).optional(),
issueId: z.string().uuid().optional(),
issueIds: z.array(z.string().uuid()).max(100).optional(),
requireIssue: z.boolean().optional(),
requireProject: z.boolean().optional(),
requireRoutine: z.boolean().optional(),
}).strict();
const credentialScopeConditionSchema = z.object({
applicationId: z.string().uuid().optional(),
applicationIds: z.array(z.string().uuid()).max(100).optional(),
connectionId: z.string().uuid().optional(),
connectionIds: z.array(z.string().uuid()).max(100).optional(),
catalogEntryId: z.string().uuid().optional(),
catalogEntryIds: z.array(z.string().uuid()).max(100).optional(),
applicationKey: z.string().trim().min(1).max(160).optional(),
applicationKeys: z.array(z.string().trim().min(1).max(160)).max(100).optional(),
providerType: z.string().trim().min(1).max(160).optional(),
providerTypes: z.array(z.string().trim().min(1).max(160)).max(100).optional(),
}).strict();
export const toolPolicyConditionsSchema = z.object({
arguments: argumentConditionSchema.optional(),
args: argumentConditionSchema.optional(),
actor: actorConditionSchema.optional(),
context: contextConditionSchema.optional(),
risk: z.object({
levels: z.array(toolRiskLevelSchema).max(20).optional(),
max: toolRiskLevelSchema.optional(),
isWrite: z.boolean().optional(),
isDestructive: z.boolean().optional(),
}).strict().optional(),
credentialScope: credentialScopeConditionSchema.optional(),
trustBoundary: z.object({
providerType: z.string().trim().min(1).max(160).optional(),
providerTypes: z.array(z.string().trim().min(1).max(160)).max(100).optional(),
applicationKey: z.string().trim().min(1).max(160).optional(),
applicationKeys: z.array(z.string().trim().min(1).max(160)).max(100).optional(),
remoteHttpOnly: z.boolean().optional(),
paperclipSelfOnly: z.boolean().optional(),
}).strict().optional(),
timeWindow: timeWindowConditionSchema.optional(),
}).strict().refine(
(value) => Object.keys(value).length > 0,
{ message: "Tool policy conditions must include at least one supported condition group" },
);
export const createToolPolicySchema = z.object({
name: z.string().trim().min(1).max(160),
description: z.string().max(4000).optional().nullable(),
policyType: toolPolicyTypeSchema,
priority: z.number().int().min(0).max(10000).default(100),
enabled: z.boolean().default(true),
selectors: z.record(z.string(), z.unknown()).default({}),
conditions: toolPolicyConditionsSchema.optional().nullable(),
config: z.record(z.string(), z.unknown()).optional().nullable(),
});
export type CreateToolPolicy = z.infer<typeof createToolPolicySchema>;
export const updateToolPolicySchema = createToolPolicySchema.partial().refine(
(value) => Object.keys(value).length > 0,
{ message: "At least one tool policy field is required" },
);
export type UpdateToolPolicy = z.infer<typeof updateToolPolicySchema>;
export const reorderToolPoliciesSchema = z.object({
policyIds: z.array(z.string().uuid()).min(1).max(500),
});
export type ReorderToolPolicies = z.infer<typeof reorderToolPoliciesSchema>;
export const duplicateToolPolicySchema = z.object({
name: z.string().trim().min(1).max(160).optional(),
});
export type DuplicateToolPolicy = z.infer<typeof duplicateToolPolicySchema>;
export const createToolInvocationSchema = z.object({
idempotencyKey: z.string().trim().min(1).max(300).optional().nullable(),
issueId: z.string().uuid().optional().nullable(),
runId: z.string().uuid().optional().nullable(),
applicationId: z.string().uuid().optional().nullable(),
connectionId: z.string().uuid().optional().nullable(),
catalogEntryId: z.string().uuid().optional().nullable(),
toolName: z.string().trim().min(1).max(240),
argumentsHash: z.string().trim().max(128).optional().nullable(),
argumentsSummary: toolRedactedValueSummarySchema.optional().nullable(),
});
export type CreateToolInvocation = z.infer<typeof createToolInvocationSchema>;
export const createToolActionRequestSchema = z.object({
invocationId: z.string().uuid(),
issueId: z.string().uuid().optional().nullable(),
canonicalArgumentsHash: z.string().trim().min(1).max(128),
canonicalArgumentsSummary: toolRedactedValueSummarySchema,
signedArguments: z.string().trim().max(4096).optional().nullable(),
previewMarkdown: z.string().max(20_000).optional().nullable(),
expiresAt: z.coerce.date().optional().nullable(),
});
export type CreateToolActionRequest = z.infer<typeof createToolActionRequestSchema>;
export const toolConnectionTestCallSchema = z.object({
agentId: z.string().uuid(),
toolName: z.string().trim().min(1).max(240),
parameters: z.unknown().optional(),
});
export type ToolConnectionTestCallInput = z.infer<typeof toolConnectionTestCallSchema>;
export const importMcpJsonSchema = z.object({
mcpJson: z.union([z.string(), z.record(z.string(), z.unknown())]),
});
export type ImportMcpJson = z.infer<typeof importMcpJsonSchema>;
export const toolAccessSelectorSchema = z.object({
actorType: z.enum(["agent", "user", "system", "plugin"]).optional(),
agentId: z.string().uuid().optional(),
agentIds: z.array(z.string().uuid()).optional(),
projectId: z.string().uuid().optional(),
projectIds: z.array(z.string().uuid()).optional(),
routineId: z.string().uuid().optional(),
routineIds: z.array(z.string().uuid()).optional(),
issueId: z.string().uuid().optional(),
issueIds: z.array(z.string().uuid()).optional(),
gatewayId: z.string().uuid().optional(),
gatewayIds: z.array(z.string().uuid()).optional(),
gatewayPublicId: z.string().trim().min(1).max(120).regex(safeKeyPattern).optional(),
gatewayPublicIds: z.array(z.string().trim().min(1).max(120).regex(safeKeyPattern)).optional(),
gatewayTokenId: z.string().uuid().optional(),
gatewayTokenIds: z.array(z.string().uuid()).optional(),
clientSubjectType: toolMcpGatewayTokenSubjectTypeSchema.optional(),
clientSubjectTypes: z.array(toolMcpGatewayTokenSubjectTypeSchema).optional(),
clientName: z.string().trim().min(1).max(160).optional(),
clientNames: z.array(z.string().trim().min(1).max(160)).optional(),
externalClient: z.boolean().optional(),
applicationId: z.string().uuid().optional(),
applicationIds: z.array(z.string().uuid()).optional(),
connectionId: z.string().uuid().optional(),
connectionIds: z.array(z.string().uuid()).optional(),
catalogEntryId: z.string().uuid().optional(),
catalogEntryIds: z.array(z.string().uuid()).optional(),
toolName: z.string().trim().min(1).max(240).optional(),
toolNames: z.array(z.string().trim().min(1).max(240)).optional(),
riskLevel: toolRiskLevelSchema.optional(),
riskLevels: z.array(toolRiskLevelSchema).optional(),
});
export const toolRateLimitRuleSchema = z.object({
limit: z.number().int().positive().max(1_000_000),
windowSeconds: z.number().int().positive().max(31_536_000),
keyBy: z.array(z.enum(["company", "agent", "application", "connection", "tool"])).optional(),
});
export const toolTrustRuleArgumentFiltersSchema = z.object({
allowAny: z.boolean().optional(),
exactHash: z.string().trim().regex(/^[a-f0-9]{64}$/i).optional().nullable(),
allowedHashes: z.array(z.string().trim().regex(/^[a-f0-9]{64}$/i)).max(100).optional(),
fieldEquals: z.record(z.string().trim().min(1).max(120), z.unknown()).optional(),
fieldNotEquals: z.record(z.string().trim().min(1).max(120), z.unknown()).optional(),
fieldIn: z.record(z.string().trim().min(1).max(120), z.array(z.unknown()).min(1).max(100)).optional(),
fieldMatches: z.record(z.string().trim().min(1).max(120), z.string().trim().min(1).max(500)).optional(),
fieldExists: z.array(z.string().trim().min(1).max(120)).max(100).optional(),
fieldAbsent: z.array(z.string().trim().min(1).max(120)).max(100).optional(),
}).refine(
(value) => value.allowAny === true
|| Boolean(value.exactHash)
|| Boolean(value.allowedHashes?.length)
|| Boolean(value.fieldEquals && Object.keys(value.fieldEquals).length > 0)
|| Boolean(value.fieldNotEquals && Object.keys(value.fieldNotEquals).length > 0)
|| Boolean(value.fieldIn && Object.keys(value.fieldIn).length > 0)
|| Boolean(value.fieldMatches && Object.keys(value.fieldMatches).length > 0)
|| Boolean(value.fieldExists?.length)
|| Boolean(value.fieldAbsent?.length),
{ message: "Trust-rule argument filters must specify allowAny, a hash filter, or a field predicate" },
);
export const toolTrustRuleScopeSchema = z.object({
includeAgent: z.boolean().optional(),
includeProject: z.boolean().optional(),
includeIssue: z.boolean().optional(),
includeApplication: z.boolean().optional(),
includeConnection: z.boolean().optional(),
includeCatalogEntry: z.boolean().optional(),
includeTool: z.boolean().optional(),
});
export const toolTrustRuleBatchApprovalSchema = z.object({
enabled: z.boolean().optional(),
maxBatchSize: z.number().int().positive().max(100).optional(),
windowSeconds: z.number().int().positive().max(31_536_000).optional(),
});
export const createToolTrustRuleFromActionRequestSchema = z.object({
name: z.string().trim().min(1).max(160).optional(),
description: z.string().max(4000).optional().nullable(),
priority: z.number().int().min(0).max(10000).default(40),
approvalThreshold: z.number().int().min(1).max(50).default(2),
selectors: toolAccessSelectorSchema.optional(),
scope: toolTrustRuleScopeSchema.optional(),
argumentFilters: toolTrustRuleArgumentFiltersSchema.optional(),
expiresAt: z.coerce.date().optional().nullable(),
batchApproval: toolTrustRuleBatchApprovalSchema.optional().nullable(),
});
export type CreateToolTrustRuleFromActionRequest = z.infer<typeof createToolTrustRuleFromActionRequestSchema>;
export const revokeToolTrustRuleSchema = z.object({
reason: z.string().trim().max(1000).optional().nullable(),
});
export type RevokeToolTrustRule = z.infer<typeof revokeToolTrustRuleSchema>;
export const toolPolicyTestRequestSchema = z.object({
companyId: z.string().uuid(),
actor: z.object({
actorType: z.enum(["agent", "user", "system", "plugin"]),
actorId: z.string().trim().min(1).max(240),
agentId: z.string().uuid().optional().nullable(),
}),
runContext: z.object({
heartbeatRunId: z.string().uuid().optional().nullable(),
issueId: z.string().uuid().optional().nullable(),
projectId: z.string().uuid().optional().nullable(),
routineId: z.string().uuid().optional().nullable(),
gatewayId: z.string().uuid().optional().nullable(),
gatewayPublicId: z.string().trim().min(1).max(120).regex(safeKeyPattern).optional().nullable(),
gatewayTokenId: z.string().uuid().optional().nullable(),
clientSubjectType: toolMcpGatewayTokenSubjectTypeSchema.optional().nullable(),
clientSubjectId: z.string().trim().min(1).max(240).optional().nullable(),
clientName: z.string().trim().min(1).max(160).optional().nullable(),
externalClient: z.boolean().optional().nullable(),
}).optional().nullable(),
request: z.object({
applicationId: z.string().uuid().optional().nullable(),
connectionId: z.string().uuid().optional().nullable(),
catalogEntryId: z.string().uuid().optional().nullable(),
toolName: z.string().trim().min(1).max(240),
arguments: z.unknown().optional(),
idempotencyKey: z.string().trim().min(1).max(512).optional().nullable(),
sideEffecting: z.boolean().optional(),
}),
consumeRateLimit: z.boolean().optional(),
writeAuditEvent: z.boolean().optional(),
});
export type ToolPolicyTestRequestInput = z.infer<typeof toolPolicyTestRequestSchema>;