mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-27 11:40:00 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The built-in Google Workspace connector gives agents Gmail, Drive, Docs, Sheets, Slides and Calendar actions through one connection > - Google's hosted Workspace MCP servers are a Developer Preview, so Paperclip cannot offer them to the public > - Paperclip has its own REST tool set for all 36 allowlisted actions, but every service still sent its calls to Google's MCP servers > - The owner decided on 2026-11-23 to launch all six services on REST now and to live-test on the staging tester after deploy > - This pull request switches the six services to `paperclip_rest` and fixes what the switch breaks > - The benefit is that the connector no longer depends on Developer Preview servers, and agents get all 36 actions, including the two Gmail actions Google's live server did not offer ## Linked Issues or Issue Description Refs #22016 (the transport switch), #22000, #22014, #22017, #22027, #22028, #22029 (the REST tool set). **Subsystem affected** Built-in Google Workspace connector (`google-workspace`, `workspace.all`): transport setting, catalog publication, tests and docs. **Problem or motivation** All six launch services used Google's hosted MCP servers. These servers are a Developer Preview and are not available to the public. Google's live Gmail MCP server also did not offer `gmail__list_threads` and `gmail__search_messages`. **Proposed solution** Set Gmail, Drive, Docs, Sheets, Slides and Calendar to `paperclip_rest` in `GOOGLE_WORKSPACE_TOOL_TRANSPORT`. Keep Chat, People and Search on `google_mcp`. Fix the catalog refresh so that an existing connection keeps its actions active after the switch. **Alternatives considered** Switch one service at a time after a live test (the Nov 17 rule). The owner replaced this rule on Nov 23: switch all six now and fix forward. **Roadmap alignment** This is the planned launch step for the Google Workspace connector. It does not overlap other core work. ## What Changed - `packages/shared/src/google-workspace-connectors.ts`: set `gmail`, `drive`, `docs`, `sheets`, `slides` and `calendar` to `paperclip_rest`. `chat`, `people` and `search` stay `google_mcp`. - Connections saved before the switch keep Google's MCP definitions in their catalog. Two changes make them work with no user action: - New resolver `paperclipDefinedTool(connection, toolName)` in `server/src/services/connectors/paperclip-defined-tools.ts` (typed result). It is the one place that says which tools are Paperclip-defined; for a `google-workspace` connection it calls `googleWorkspaceRestToolDefinition` in the dispatch adapter, which returns the REST definition when the service is on `paperclip_rest`. - `server/src/services/tool-gateway.ts`: when the gateway lists a connection's tools, it takes the input schema, output schema, description and annotations of a Paperclip-defined tool from the resolver, not from the saved row. Routing and the advertised definition read the same transport setting in the same process. This is an in-memory lookup, so it adds no request to the turn start. Example: an agent gets the REST `docs__update_doc` schema, where `writeControl.requiredRevisionId` is required, not Google's schema, where it is optional. - `server/src/services/tool-access/catalog/publication.ts`: catalog publication asks the same resolver. It never holds a Paperclip-defined action for review, and it clears the review hold (`quarantined`, `pending_review`) of an action held only because a remote definition changed. Clearing the hold does not count the action as new, so it is never added to the profile: Off stays Off and Ask first stays, also for a held action. Only actions the connection never had (Gmail `list_threads` and `search_messages`) get the default for new actions. Before this fix, a refresh after the switch put every action of an existing managed connection into `pending_review` (10 of 10 in the regression test). - `server/src/__tests__/google-workspace-rest-transport.test.ts`: the fake Google now answers the Docs, Sheets and Slides REST hosts and the Drive and Calendar paths. New tests: - The transport map has exactly the six launch services on `paperclip_rest`. - A full read and write grant lists exactly the 36 allowlisted actions (with `gmail__list_threads` and `gmail__search_messages`) and sends no MCP request. A read-only grant lists the 23 read actions. Gmail, Drive and Calendar group grants list exactly their actions. - One read and one write per service run through the real `executeTool` path on REST with the default policy (no approval request). Each call records the invocation and the `call_completed` event with the connection ID (the "Delete data" bookkeeping keys), and audits the protocol `Google Workspace REST` with the service endpoint. - Injected instructions in Docs, Sheets, Slides, Drive and Calendar REST results are blocked. - An existing connection discovered over MCP keeps its actions active after the switch and can call the new Gmail actions. - Migration without refresh: a connection saved with Google's MCP schemas (`update_doc` with `writeControl` optional) advertises the REST schemas after the switch with no refresh, and `read_doc` then `update_doc` with the revision succeed over REST. - The first refresh after the switch releases an action held for `pending_review`, keeps an Off action unlisted and keeps Ask first (`approval_required`). - An action that is both Off and held stays Off, and one that is both Ask first and held stays Ask first, after the switch and after two refreshes. - The MCP-path test pins Gmail and Docs to `google_mcp` explicitly. - `server/src/__tests__/helpers/google-workspace-transport.ts`: new helper `useGoogleMcpTransport()`. Tests whose fixtures act as Google's MCP servers use it (`tool-access-service`, `tool-gateway-service`) or pin the transport in `beforeAll` (`google-workspace-injection-screening`). These tests still cover the MCP path, which stays available for Chat, People, Search and a switch back. - `packages/shared/src/google-workspace-connectors.test.ts`: assert the new transport map. - Docs: `doc/connections/GOOGLE-WORKSPACE.md` and the REST folder `README.md` say that the six services run on REST. `doc/memory/google-connector-memory.md` has three dated Nov 23 decisions (all six switched to REST, writes default to Allowed, image-by-URL inserts allowed), and the two items are removed from "Still open". ## Verification - Red: after the flip, 50 tests failed in four files because their fixtures act as Google's MCP servers. These are fixture assumptions, not product bugs. - Red: without the gateway change, the migration test gets Google's saved schema; without the publication change, the held action stays `quarantined`; without excluding released rows from the new-action default, the Off and held action comes back. All green with the fixes. - Red: the new test "keeps an existing connection's actions usable when its services move from Google's MCP servers to REST" failed before the `publication.ts` fix: 10 catalog entries were `quarantined` with `pending_review`. Green after the fix. - `cd server && npx vitest run src/__tests__/google-workspace-rest-transport.test.ts src/__tests__/google-workspace-injection-screening.test.ts src/__tests__/tool-gateway-service.test.ts src/__tests__/tool-access-service.test.ts src/services/google-workspace-rest-dispatch.test.ts src/google-workspace-rest-tools`: with `connection-management.integration.test.ts` added: 60 files, 2232 tests pass. `google-workspace-rest-transport.test.ts`: 52 tests pass. - `cd packages/shared && npx vitest run src/google-workspace-connectors.test.ts`: 14 tests pass. - `npx tsc -p server/tsconfig.json --noEmit`: no errors. - Trace of a read (`gmail__get_message`) and a write (`gmail__create_draft`) through `executeTool` in `server/src/services/tool-gateway.ts`: policy decision and invocation record (13723, 13731), approval gate (13820), `call_allowed` audit (13885), dispatch to `executeRemoteHttpTool` (13915), prompt-injection screening of the result (13964), `call_completed` event and audit (14022, 14044), failure audit (14187). In `executeRemoteHttpTool` the grant scope check (8172) runs before the REST branch (8276), which rechecks the current grant and returns before any MCP session, MCP Task or elicitation code. The REST adapter (`google-workspace-rest-dispatch.ts`) calls `google-http.ts` only through the gateway's guarded fetch. - Not verified: calls against real Google. The live test on the staging tester runs after deploy. ## Risks - Real Google answers can differ from the fixtures. The REST tools are not yet run against real Google. The live test on the staging tester runs after this deploys, and problems are fixed forward. - The OAuth client on the staging tester is marked for AI agents and was only used through MCP. If Google refuses REST calls from that client, all six services fail on the tester until the client changes. - Existing connections keep their stored MCP schemas until a catalog refresh, but agents receive the REST definitions at once. The stored risk level of the four update actions stays `write` until that refresh, then becomes `destructive`. The two new Gmail actions appear after a refresh. - Input differences between Google's MCP schemas and the REST tools are listed in the REST folder `README.md` ("Input differences an agent meets after a switch"). Agents receive the REST schemas, so these differences are visible to them. No `tools/list` from Google's servers is recorded, so the check uses Google's published references. - Accepted risk (owner decision, 2026-11-23): Docs and Slides edits may insert an image from any public web address. Google, not Paperclip, fetches the address, and Paperclip's own requests still go only to the allowed Google hosts. The residual risk is that an agent could put data in the address it chooses. Links to Drive or Docs files stay refused. - Update actions (`update_doc`, `update_presentation`, `update_spreadsheet`, `update_event`) are labelled destructive on REST, as decided on Nov 17. This does not add an approval step: write actions stay Allowed by default. - A switch back to `google_mcp` stays possible with a one-line change. The MCP path tests still run. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test runs). ## 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] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
252 lines
15 KiB
TypeScript
252 lines
15 KiB
TypeScript
export const GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS = [
|
|
"gmail.read", "gmail.draft", "gmail.archive", "drive.read", "drive.write", "docs.read", "docs.write",
|
|
"sheets.read", "sheets.write", "slides.read", "slides.write", "calendar.read",
|
|
"calendar.write", "chat.read", "chat.write", "people.read", "workspace-search.read",
|
|
"workspace.all",
|
|
] as const;
|
|
|
|
export type GoogleWorkspaceConnectorProfileId = (typeof GOOGLE_WORKSPACE_CONNECTOR_PROFILE_IDS)[number];
|
|
|
|
export type GoogleWorkspaceServiceSelection = Partial<Record<"gmail" | "drive" | "calendar", "read" | "write">>;
|
|
export const GOOGLE_WORKSPACE_DEFAULT_SELECTION: GoogleWorkspaceServiceSelection = { gmail: "write", drive: "write", calendar: "write" };
|
|
export const GOOGLE_WORKSPACE_SERVICE_GROUPS = [
|
|
{ id: "gmail", name: "Gmail", brandKey: "gmail", read: ["gmail.read"], write: ["gmail.draft"] },
|
|
{ id: "drive", name: "Drive", brandKey: "google-drive", description: "Docs, Sheets, and Slides", read: ["drive.read", "docs.read", "sheets.read", "slides.read"], write: ["drive.write", "docs.write", "sheets.write", "slides.write"] },
|
|
{ id: "calendar", name: "Calendar", brandKey: "google-calendar", read: ["calendar.read"], write: ["calendar.write"] },
|
|
] as const;
|
|
|
|
/** Derive resource permissions from closed service groups, never client-supplied scope strings. */
|
|
export function googleWorkspaceSelectedScopes(selection: GoogleWorkspaceServiceSelection): string[] {
|
|
return [...new Set(GOOGLE_WORKSPACE_SERVICE_GROUPS.flatMap(group => {
|
|
const access = selection[group.id];
|
|
return access ? [
|
|
...group[access].flatMap(profile => GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes),
|
|
...(SELECTION_ADDED_SCOPES[group.id]?.[access] ?? []),
|
|
] : [];
|
|
}))].sort();
|
|
}
|
|
|
|
/** Keep provider consent inside this request, including a provider's read-only downgrade. */
|
|
export function googleWorkspaceEffectiveScopes(requested: readonly string[], granted: readonly string[]): string[] {
|
|
const implies: Record<string, string[]> = {
|
|
documents: ["documents.readonly"], spreadsheets: ["spreadsheets.readonly"],
|
|
presentations: ["presentations.readonly"],
|
|
"calendar.events": ["calendar.events.readonly"],
|
|
"calendar.readonly": ["calendar.calendarlist.readonly", "calendar.events.readonly", "calendar.events.freebusy"],
|
|
};
|
|
const expand = (scopes: readonly string[]) => new Set(scopes.flatMap(scope => [scope, ...(implies[scope.replace("https://www.googleapis.com/auth/", "")] ?? []).map(value => `https://www.googleapis.com/auth/${value}`)]));
|
|
const allowed = expand(requested);
|
|
const effective = [...expand(granted)].filter(scope => allowed.has(scope));
|
|
return effective.filter(scope => !effective.some(broader => broader !== scope && (implies[broader.replace("https://www.googleapis.com/auth/", "")] ?? []).some(value => scope === `https://www.googleapis.com/auth/${value}`))).sort();
|
|
}
|
|
|
|
export function googleWorkspaceSelectionForScopes(scopes: readonly string[]): GoogleWorkspaceServiceSelection {
|
|
const selection: GoogleWorkspaceServiceSelection = {};
|
|
for (const group of GOOGLE_WORKSPACE_SERVICE_GROUPS) {
|
|
const writes = group.write.flatMap(profile => GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes);
|
|
const reads = group.read.flatMap(profile => GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes);
|
|
if (writes.every(scope => scopes.includes(scope))) selection[group.id] = "write";
|
|
else if (reads.some(scope => scopes.includes(scope))) selection[group.id] = "read";
|
|
}
|
|
return selection;
|
|
}
|
|
|
|
export interface GoogleWorkspaceDraftBinding {
|
|
companyId: string;
|
|
connectionId: string;
|
|
actorType: string | null;
|
|
actorId: string | null;
|
|
grantKind: "user" | "agent" | "organization";
|
|
subjectId: string | null;
|
|
}
|
|
|
|
export function googleWorkspaceDraftRequestedScopes(
|
|
value: unknown,
|
|
binding: GoogleWorkspaceDraftBinding,
|
|
): string[] | null {
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
const draft = value as Record<string, unknown>;
|
|
if (!binding.actorType || !binding.actorId || draft.version !== 1
|
|
|| Object.entries(binding).some(([key, expected]) => draft[key] !== expected)) return null;
|
|
const scopes = draft.requestedScopes;
|
|
const allowed = new Set(GOOGLE_WORKSPACE_SERVICE_GROUPS.flatMap(group =>
|
|
[...group.read, ...group.write].flatMap(profile => GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes)));
|
|
if (!Array.isArray(scopes) || scopes.length === 0 || scopes.length > allowed.size
|
|
|| scopes.some(scope => typeof scope !== "string" || !allowed.has(scope))) return null;
|
|
return [...new Set(scopes)].sort();
|
|
}
|
|
|
|
const auth = (scope: string) => `https://www.googleapis.com/auth/${scope}`;
|
|
|
|
const SELECTION_ADDED_SCOPES: Partial<Record<keyof GoogleWorkspaceServiceSelection, Partial<Record<"read" | "write", readonly string[]>>>> = {
|
|
calendar: { write: [auth("calendar.events.freebusy")] },
|
|
};
|
|
|
|
const SERVICE_PROFILES: Readonly<Record<Exclude<GoogleWorkspaceConnectorProfileId, "workspace.all">, {
|
|
appSlug: string;
|
|
serverUrl: string;
|
|
scopes: readonly string[];
|
|
writeTools: readonly string[];
|
|
}>> = {
|
|
"gmail.read": def("gmail", "https://gmailmcp.googleapis.com/mcp/v1", [auth("gmail.readonly")]),
|
|
"gmail.draft": def("gmail", "https://gmailmcp.googleapis.com/mcp/v1", [auth("gmail.readonly"), auth("gmail.compose")], ["create_draft"]),
|
|
"gmail.archive": def("gmail", "https://gmailmcp.googleapis.com/mcp/v1", [auth("gmail.readonly"), auth("gmail.modify")], ["unlabel_thread"]),
|
|
"drive.read": def("google-drive", "https://drivemcp.googleapis.com/mcp/v1", [auth("drive.readonly")]),
|
|
"drive.write": def("google-drive", "https://drivemcp.googleapis.com/mcp/v1", [auth("drive.readonly"), auth("drive.file")], ["copy_file", "create_file"]),
|
|
"docs.read": def("google-docs", "https://docsmcp.googleapis.com/mcp/v1", [auth("documents.readonly")]),
|
|
"docs.write": def("google-docs", "https://docsmcp.googleapis.com/mcp/v1", [auth("documents")], ["update_doc"]),
|
|
"sheets.read": def("google-sheets", "https://sheetsmcp.googleapis.com/mcp/v1", [auth("spreadsheets.readonly")]),
|
|
"sheets.write": def("google-sheets", "https://sheetsmcp.googleapis.com/mcp/v1", [auth("spreadsheets")], ["update_spreadsheet", "update_values", "update_formulas", "insert_dimension"]),
|
|
"slides.read": def("google-slides", "https://slidesmcp.googleapis.com/mcp/v1", [auth("presentations.readonly")]),
|
|
"slides.write": def("google-slides", "https://slidesmcp.googleapis.com/mcp/v1", [auth("presentations")], ["update_presentation"]),
|
|
"calendar.read": def("google-calendar", "https://calendarmcp.googleapis.com/mcp/v1", [auth("calendar.calendarlist.readonly"), auth("calendar.events.freebusy"), auth("calendar.events.readonly")]),
|
|
"calendar.write": def("google-calendar", "https://calendarmcp.googleapis.com/mcp/v1", [auth("calendar.calendarlist.readonly"), auth("calendar.events")], ["create_event", "update_event", "delete_event", "respond_to_event"]),
|
|
"chat.read": def("google-chat", "https://chatmcp.googleapis.com/mcp/v1", [auth("chat.spaces.readonly"), auth("chat.messages.readonly")]),
|
|
"chat.write": def("google-chat", "https://chatmcp.googleapis.com/mcp/v1", [auth("chat.spaces.readonly"), auth("chat.messages.readonly"), auth("chat.messages.create")], ["send_message"]),
|
|
"people.read": def("google-people", "https://people.googleapis.com/mcp/v1", [auth("directory.readonly"), auth("userinfo.profile"), auth("contacts.readonly")]),
|
|
"workspace-search.read": def("google-workspace-search", "https://workspacemcp.googleapis.com/mcp/v1", [auth("gmail.readonly"), auth("drive.readonly"), auth("calendar.readonly"), auth("chat.messages.readonly")]),
|
|
};
|
|
|
|
export const GOOGLE_WORKSPACE_SUBMITTED_SCOPES: readonly string[] = Object.freeze([
|
|
"gmail.readonly", "gmail.compose",
|
|
"drive.readonly", "drive.file",
|
|
"documents.readonly", "documents",
|
|
"spreadsheets.readonly", "spreadsheets",
|
|
"presentations.readonly", "presentations",
|
|
"calendar.calendarlist.readonly", "calendar.events.readonly", "calendar.events.freebusy", "calendar.events",
|
|
].map(auth));
|
|
|
|
/** One consent request, containing only scopes already reviewed for our services. */
|
|
export const GOOGLE_WORKSPACE_CONNECTOR_PROFILES = {
|
|
...SERVICE_PROFILES,
|
|
"workspace.all": def("google-workspace", "https://workspacemcp.googleapis.com/mcp/v1", GOOGLE_WORKSPACE_SUBMITTED_SCOPES),
|
|
};
|
|
|
|
export function googleWorkspaceProfileWithinSubmittedScopes(profile: GoogleWorkspaceConnectorProfileId): boolean {
|
|
return GOOGLE_WORKSPACE_CONNECTOR_PROFILES[profile].scopes.every((scope) => GOOGLE_WORKSPACE_SUBMITTED_SCOPES.includes(scope));
|
|
}
|
|
|
|
export const GOOGLE_WORKSPACE_SERVICES = {
|
|
gmail: "gmail.draft", drive: "drive.write", docs: "docs.write", sheets: "sheets.write",
|
|
slides: "slides.write", calendar: "calendar.write", chat: "chat.write",
|
|
people: "people.read", search: "workspace-search.read",
|
|
} as const;
|
|
export type GoogleWorkspaceService = keyof typeof GOOGLE_WORKSPACE_SERVICES;
|
|
|
|
export type GoogleWorkspaceToolTransport = "google_mcp" | "paperclip_rest";
|
|
|
|
export const GOOGLE_WORKSPACE_TOOL_TRANSPORT: Record<GoogleWorkspaceService, GoogleWorkspaceToolTransport> = {
|
|
gmail: "paperclip_rest", drive: "paperclip_rest", docs: "paperclip_rest", sheets: "paperclip_rest",
|
|
slides: "paperclip_rest", calendar: "paperclip_rest", chat: "google_mcp",
|
|
people: "google_mcp", search: "google_mcp",
|
|
};
|
|
|
|
// Each inner group is a set of authorization alternatives; every group is required.
|
|
// Keep the reviewed tool allowlist closed, even when upstream adds tools.
|
|
const one = (...scopes: string[]) => [scopes.map(auth)];
|
|
const toolScopes: Record<GoogleWorkspaceService, Record<string, string[][]>> = {
|
|
gmail: Object.fromEntries([
|
|
...["get_message", "get_thread", "get_draft", "list_drafts", "list_labels", "search_threads", "list_threads", "search_messages"]
|
|
.map((name) => [name, one("gmail.readonly")]),
|
|
["create_draft", one("gmail.compose")],
|
|
]),
|
|
drive: Object.fromEntries([
|
|
...["download_file_content", "get_file_metadata", "get_file_permissions", "list_recent_files", "read_file_content", "search_files"]
|
|
.map((name) => [name, one("drive.readonly")]),
|
|
...["copy_file", "create_file"].map((name) => [name, one("drive.file")]),
|
|
]),
|
|
docs: { read_doc: one("documents.readonly", "documents"), update_doc: one("documents") },
|
|
sheets: Object.fromEntries([
|
|
...["get_values", "get_spreadsheet"].map((name) => [name, one("spreadsheets.readonly", "spreadsheets")]),
|
|
...["update_spreadsheet", "update_values", "update_formulas", "insert_dimension"].map((name) => [name, one("spreadsheets")]),
|
|
]),
|
|
slides: { read_presentation: one("presentations.readonly", "presentations"), update_presentation: one("presentations") },
|
|
calendar: Object.fromEntries([
|
|
["list_calendars", one("calendar.calendarlist.readonly", "calendar.readonly")],
|
|
...["get_event", "list_events", "search_events"].map((name) => [name, one("calendar.events.readonly", "calendar.events", "calendar.readonly")]),
|
|
["suggest_time", one("calendar.events.freebusy", "calendar.events", "calendar.readonly")],
|
|
...["create_event", "update_event", "delete_event", "respond_to_event"].map((name) => [name, one("calendar.events")]),
|
|
]),
|
|
chat: {
|
|
search_conversations: one("chat.spaces.readonly"),
|
|
list_messages: one("chat.messages.readonly"), search_messages: one("chat.messages.readonly"),
|
|
send_message: one("chat.messages.create"),
|
|
},
|
|
people: {
|
|
search_directory_people: one("directory.readonly"), search_contacts: one("contacts.readonly"),
|
|
get_user_profile: one("userinfo.profile"),
|
|
},
|
|
search: { search_corpus: SERVICE_PROFILES["workspace-search.read"].scopes.map((scope) => [scope]) },
|
|
};
|
|
|
|
export function googleWorkspaceToolName(service: GoogleWorkspaceService, upstreamName: string): string {
|
|
return `${service}__${upstreamName}`;
|
|
}
|
|
|
|
/** The endpoint is derived from a closed registry, never provider annotations or caller input. */
|
|
export function googleWorkspaceToolTarget(name: string) {
|
|
const separator = name.indexOf("__");
|
|
const service = name.slice(0, separator) as GoogleWorkspaceService;
|
|
if (separator < 1 || !Object.hasOwn(GOOGLE_WORKSPACE_SERVICES, service)) return null;
|
|
const upstreamName = name.slice(separator + 2);
|
|
const leaf = (upstreamName.split(/[.:/]/).pop() ?? upstreamName)
|
|
.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/-/g, "_").toLowerCase();
|
|
if (!Object.hasOwn(toolScopes[service], leaf)) return null;
|
|
const profile = SERVICE_PROFILES[GOOGLE_WORKSPACE_SERVICES[service]];
|
|
return { service, upstreamName, leaf, serverUrl: profile.serverUrl, appSlug: profile.appSlug,
|
|
requiredScopes: toolScopes[service][leaf]!, write: profile.writeTools.some((tool) => tool === leaf),
|
|
transport: GOOGLE_WORKSPACE_TOOL_TRANSPORT[service] };
|
|
}
|
|
|
|
const GOOGLE_WORKSPACE_SERVICE_TITLES: Record<GoogleWorkspaceService, string> = {
|
|
gmail: "Gmail", drive: "Drive", docs: "Docs", sheets: "Sheets", slides: "Slides",
|
|
calendar: "Calendar", chat: "Chat", people: "People", search: "Workspace search",
|
|
};
|
|
|
|
export function googleWorkspaceToolTitle(name: string, title?: string | null): string | null {
|
|
const target = googleWorkspaceToolTarget(name);
|
|
const given = title?.trim() || null;
|
|
if (!target) return given;
|
|
const service = GOOGLE_WORKSPACE_SERVICE_TITLES[target.service];
|
|
if (given?.startsWith(`${service}: `)) return given;
|
|
const leaf = target.leaf.replace(/_/g, " ");
|
|
return `${service}: ${given ?? leaf.charAt(0).toUpperCase() + leaf.slice(1)}`;
|
|
}
|
|
|
|
export function googleWorkspaceServiceToolNames(service: GoogleWorkspaceService): string[] {
|
|
return Object.keys(toolScopes[service]);
|
|
}
|
|
|
|
export function isGoogleWorkspaceToolGranted(name: string, scopes: readonly string[]): boolean {
|
|
const target = googleWorkspaceToolTarget(name);
|
|
return Boolean(target && target.requiredScopes.every((alternatives) => alternatives.some((scope) => scopes.includes(scope))));
|
|
}
|
|
|
|
export function googleWorkspaceSubmittedScopesIn(scopes: readonly string[]): string[] {
|
|
return [...new Set(scopes.filter((scope) => GOOGLE_WORKSPACE_SUBMITTED_SCOPES.includes(scope)))];
|
|
}
|
|
|
|
export function isGoogleWorkspaceScopeGrant(scopes: readonly string[]): boolean {
|
|
return scopes.length > 0 && scopes.every((scope) => GOOGLE_WORKSPACE_SUBMITTED_SCOPES.includes(scope));
|
|
}
|
|
|
|
export function googleWorkspaceServiceGranted(service: GoogleWorkspaceService, scopes: readonly string[]): boolean {
|
|
return Object.keys(toolScopes[service]).some((name) => isGoogleWorkspaceToolGranted(googleWorkspaceToolName(service, name), scopes));
|
|
}
|
|
|
|
/** Requested scopes and connection-wide defaults are never evidence of consent. */
|
|
export function googleWorkspaceGrantedScopes(grant: { providerTenant?: unknown } | null): string[] {
|
|
const tenant = grant?.providerTenant as { oauth?: { scopes?: unknown; scopeSource?: unknown } } | undefined;
|
|
const oauth = tenant?.oauth;
|
|
if (oauth?.scopeSource === "requested_fallback" || !Array.isArray(oauth?.scopes)) return [];
|
|
return oauth.scopes.filter((scope): scope is string => typeof scope === "string");
|
|
}
|
|
|
|
export function isGoogleWorkspaceConnectorProfileId(value: string): value is GoogleWorkspaceConnectorProfileId {
|
|
return Object.prototype.hasOwnProperty.call(GOOGLE_WORKSPACE_CONNECTOR_PROFILES, value);
|
|
}
|
|
|
|
function def(appSlug: string, serverUrl: string, scopes: readonly string[], writeTools: readonly string[] = []) {
|
|
return { appSlug, serverUrl, scopes, writeTools };
|
|
}
|