mcp-google-contacts 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +306 -0
- package/README.ru.md +306 -0
- package/dist/client.js +561 -0
- package/dist/config.js +83 -0
- package/dist/index.js +126 -0
- package/dist/telemetry.js +120 -0
- package/dist/tools/batch.js +71 -0
- package/dist/tools/contacts.js +150 -0
- package/dist/tools/groups.js +123 -0
- package/dist/tools/other.js +62 -0
- package/dist/tools/raw.js +30 -0
- package/dist/tools/util.js +221 -0
- package/dist/types.js +48 -0
- package/package.json +60 -0
- package/test/dist-smoke.test.js +176 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
import { GoogleContactsClient } from "./client.js";
|
|
6
|
+
import { ConfigError, DEFAULT_BASE, hasCredentials, loadConfig } from "./config.js";
|
|
7
|
+
import { instrumentToolCalls, Telemetry } from "./telemetry.js";
|
|
8
|
+
import { registerContactTools } from "./tools/contacts.js";
|
|
9
|
+
import { registerGroupTools } from "./tools/groups.js";
|
|
10
|
+
import { registerBatchTools } from "./tools/batch.js";
|
|
11
|
+
import { registerOtherContactTools } from "./tools/other.js";
|
|
12
|
+
import { registerRawTool } from "./tools/raw.js";
|
|
13
|
+
/**
|
|
14
|
+
* Prose handed to the calling model in the `initialize` result — the only place
|
|
15
|
+
* it learns what the tool list cannot say: which Google product this API is,
|
|
16
|
+
* what the API refuses to do, and the behaviours that make a naive loop
|
|
17
|
+
* expensive, lossy or duplicating.
|
|
18
|
+
*/
|
|
19
|
+
const INSTRUCTIONS = "Google People API v1 manages the signed-in account's personal Google Contacts — not the Workspace " +
|
|
20
|
+
"directory and not other users' address books; Gmail's auto-saved \"Other contacts\" live outside the " +
|
|
21
|
+
"saved list and have their own tools (list_other_contacts, copy_other_contact) plus their own OAuth " +
|
|
22
|
+
"scope. Every read takes an explicit person_fields/read_mask; an omitted mask gets the compact default " +
|
|
23
|
+
"(names, emailAddresses, phoneNumbers, organizations, memberships), and absent fields in a response " +
|
|
24
|
+
"mean 'not requested or empty', not lost data. " +
|
|
25
|
+
"Writes are etag-guarded: update_contact and batch_update_contacts auto-fetch the current etag when you " +
|
|
26
|
+
"omit it, and a stale etag fails with 400 — re-read, then retry deliberately. Updates REPLACE each " +
|
|
27
|
+
"provided field as a whole (all emails, the whole name): read the contact first and send complete values, " +
|
|
28
|
+
"or you will silently drop data. search_contacts indexes writes with a lag of seconds to minutes and " +
|
|
29
|
+
"caps page_size at 30 — a just-created contact is found by list_contacts/get_contact but not yet by " +
|
|
30
|
+
"search. There is no duplicate detection: a repeated create makes a second contact, so after a timeout " +
|
|
31
|
+
"or 5xx on any write (they are never auto-retried) check what committed via list/get before re-sending. " +
|
|
32
|
+
"delete_contact and batch_delete_contacts are permanent — this API has no trash. Contact groups: only " +
|
|
33
|
+
"USER_CONTACT_GROUP labels can be renamed/deleted; system groups (myContacts, starred) are fixed, and " +
|
|
34
|
+
"modify_group_members' HTTP 200 still carries per-contact failures (notFoundResourceNames) — read the " +
|
|
35
|
+
"body. Per-user per-minute quotas are tight (~90 requests/min class): prefer batch_get_contacts and " +
|
|
36
|
+
"sync tokens (request_sync_token/sync_token in list_contacts; HTTP 410 means the token expired — do a " +
|
|
37
|
+
"full re-list) over polling loops. Auth that suddenly breaks usually means the OAuth consent screen is " +
|
|
38
|
+
"still in Testing, where refresh tokens die after 7 days.";
|
|
39
|
+
/**
|
|
40
|
+
* Prepended to INSTRUCTIONS when no credentials are configured. The model reads
|
|
41
|
+
* this before it picks a tool, so an unconfigured session opens with the fix
|
|
42
|
+
* rather than with a failed call. There is no in-chat login here: credentials
|
|
43
|
+
* come only from the environment, so the fix is an operator action + restart.
|
|
44
|
+
*/
|
|
45
|
+
const UNCONFIGURED_PREFIX = "ATTENTION: Google Contacts is not connected yet — no credentials are configured, so every " +
|
|
46
|
+
"tool call will fail. The operator must set GOOGLE_CONTACTS_CLIENT_ID + " +
|
|
47
|
+
"GOOGLE_CONTACTS_CLIENT_SECRET + GOOGLE_CONTACTS_REFRESH_TOKEN (recommended), or " +
|
|
48
|
+
"GOOGLE_CONTACTS_ACCESS_TOKEN with a short-lived access token, in the MCP client's " +
|
|
49
|
+
"server config and restart this server — the variables are read only at startup. ";
|
|
50
|
+
/** Reads the package version so the server reports its real version to MCP clients. */
|
|
51
|
+
function readVersion() {
|
|
52
|
+
try {
|
|
53
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
54
|
+
return typeof pkg.version === "string" ? pkg.version : "0.0.0";
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return "0.0.0";
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Loads the config without dying on a bad value. A server that exits here never
|
|
62
|
+
* completes the MCP handshake, so the user sees a dead server and no reason.
|
|
63
|
+
* Instead the problem is carried into the session, where the model can read it
|
|
64
|
+
* and relay it: the config degrades to "no credentials" and every tool call
|
|
65
|
+
* fails with the actionable message.
|
|
66
|
+
*/
|
|
67
|
+
function loadConfigOrDegraded(telemetry) {
|
|
68
|
+
try {
|
|
69
|
+
return { config: loadConfig() };
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
if (!(err instanceof ConfigError))
|
|
73
|
+
throw err;
|
|
74
|
+
console.error(`Error: ${err.message}`);
|
|
75
|
+
// Fire-and-forget now that the process survives: the historical
|
|
76
|
+
// `startup_failed` funnel stays comparable, but nothing blocks startup.
|
|
77
|
+
telemetry.send("startup_failed", { reason: err.reason });
|
|
78
|
+
return {
|
|
79
|
+
config: { apiBase: process.env.GOOGLE_CONTACTS_API_BASE || DEFAULT_BASE },
|
|
80
|
+
problem: err,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function main() {
|
|
85
|
+
// Anonymous usage pings (ids/names/versions only, never data or arguments);
|
|
86
|
+
// opt out with ASKADS_TELEMETRY=0. Built before the config so missing
|
|
87
|
+
// credentials can be reported; wired to the server before tools register.
|
|
88
|
+
const telemetry = new Telemetry(readVersion());
|
|
89
|
+
const { config, problem } = loadConfigOrDegraded(telemetry);
|
|
90
|
+
const client = new GoogleContactsClient(config);
|
|
91
|
+
// Decided once, at startup: credentials come only from the environment, so
|
|
92
|
+
// "restart after setting the variables" is the accurate advice to give.
|
|
93
|
+
const connected = hasCredentials(config);
|
|
94
|
+
const server = new McpServer({
|
|
95
|
+
name: "mcp-google-contacts",
|
|
96
|
+
version: readVersion(),
|
|
97
|
+
},
|
|
98
|
+
// Surfaces in the initialize result, before the client sees a single tool.
|
|
99
|
+
{
|
|
100
|
+
instructions: connected
|
|
101
|
+
? INSTRUCTIONS
|
|
102
|
+
: UNCONFIGURED_PREFIX + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
|
|
103
|
+
});
|
|
104
|
+
instrumentToolCalls(server, telemetry);
|
|
105
|
+
server.server.oninitialized = () => {
|
|
106
|
+
telemetry.setClientInfo(server.server.getClientVersion());
|
|
107
|
+
// Split on purpose: `server_start` keeps meaning "a usable install started",
|
|
108
|
+
// so the unconfigured case gets its own event instead of inflating that number.
|
|
109
|
+
if (connected)
|
|
110
|
+
telemetry.send("server_start");
|
|
111
|
+
else
|
|
112
|
+
telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
|
|
113
|
+
};
|
|
114
|
+
registerContactTools(server, client);
|
|
115
|
+
registerGroupTools(server, client);
|
|
116
|
+
registerBatchTools(server, client);
|
|
117
|
+
registerOtherContactTools(server, client);
|
|
118
|
+
registerRawTool(server, client);
|
|
119
|
+
const transport = new StdioServerTransport();
|
|
120
|
+
await server.connect(transport);
|
|
121
|
+
console.error(`mcp-google-contacts running on stdio${connected ? "" : " (no credentials — set the environment variables and restart)"}`);
|
|
122
|
+
}
|
|
123
|
+
main().catch((err) => {
|
|
124
|
+
console.error("Fatal error starting mcp-google-contacts:", err);
|
|
125
|
+
process.exit(1);
|
|
126
|
+
});
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anonymous usage telemetry — fire-and-forget pings to usage.gistrec.cloud.
|
|
3
|
+
*
|
|
4
|
+
* Privacy contract (mirrored by the receiver): only an anonymous random
|
|
5
|
+
* instance id, event/tool names, a fixed-vocabulary failure reason and
|
|
6
|
+
* environment versions ever leave the machine. The OAuth credentials, contact
|
|
7
|
+
* data, tool arguments, prompts and the names or values of environment
|
|
8
|
+
* variables are never read, serialized or sent. Sends are capped at 2 s and
|
|
9
|
+
* swallow every error — telemetry must never affect the server's operation.
|
|
10
|
+
* Opt out for every server of this line at once: ASKADS_TELEMETRY=0
|
|
11
|
+
* (also accepts false/off/no).
|
|
12
|
+
*/
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
const ENDPOINT = "https://usage.gistrec.cloud/v1/events";
|
|
18
|
+
const APP = "mcp-google-contacts";
|
|
19
|
+
const SEND_TIMEOUT_MS = 2000;
|
|
20
|
+
export function telemetryEnabled(env = process.env) {
|
|
21
|
+
const value = (env.ASKADS_TELEMETRY ?? "").trim().toLowerCase();
|
|
22
|
+
return !["0", "false", "off", "no"].includes(value);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Stable anonymous installation id, persisted under the user's config dir.
|
|
26
|
+
* Any filesystem failure degrades to an ephemeral id: the ping still counts
|
|
27
|
+
* today's activity, just not installation uniqueness across restarts.
|
|
28
|
+
*/
|
|
29
|
+
function loadInstanceId() {
|
|
30
|
+
try {
|
|
31
|
+
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
32
|
+
const dir = join(base, APP);
|
|
33
|
+
const file = join(dir, "instance-id");
|
|
34
|
+
try {
|
|
35
|
+
const existing = readFileSync(file, "utf8").trim();
|
|
36
|
+
if (/^[0-9a-f]{8}-[0-9a-f-]{27}$/.test(existing))
|
|
37
|
+
return existing;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// first run — fall through and mint one
|
|
41
|
+
}
|
|
42
|
+
const id = randomUUID();
|
|
43
|
+
mkdirSync(dir, { recursive: true });
|
|
44
|
+
writeFileSync(file, `${id}\n`);
|
|
45
|
+
return id;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return randomUUID();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export class Telemetry {
|
|
52
|
+
appVersion;
|
|
53
|
+
enabled;
|
|
54
|
+
fetchImpl;
|
|
55
|
+
instanceId;
|
|
56
|
+
clientInfo;
|
|
57
|
+
constructor(appVersion, enabled = telemetryEnabled(), fetchImpl = fetch) {
|
|
58
|
+
this.appVersion = appVersion;
|
|
59
|
+
this.enabled = enabled;
|
|
60
|
+
this.fetchImpl = fetchImpl;
|
|
61
|
+
this.instanceId = enabled ? loadInstanceId() : "";
|
|
62
|
+
}
|
|
63
|
+
/** The MCP initialize handshake tells us which agent host is on the other side. */
|
|
64
|
+
setClientInfo(info) {
|
|
65
|
+
this.clientInfo = info;
|
|
66
|
+
}
|
|
67
|
+
/** Fire-and-forget: the server's own work never waits on a ping. */
|
|
68
|
+
send(event, fields = {}) {
|
|
69
|
+
void this.post(event, fields);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The same ping, awaited. Only for a caller that exits right after — a
|
|
73
|
+
* fire-and-forget request would die in flight with the process. No startup
|
|
74
|
+
* path needs it anymore (a config problem degrades instead of exiting).
|
|
75
|
+
*/
|
|
76
|
+
async sendBlocking(event, fields = {}) {
|
|
77
|
+
await this.post(event, fields);
|
|
78
|
+
}
|
|
79
|
+
async post(event, fields) {
|
|
80
|
+
if (!this.enabled)
|
|
81
|
+
return;
|
|
82
|
+
const body = JSON.stringify({
|
|
83
|
+
app: APP,
|
|
84
|
+
event,
|
|
85
|
+
instance_id: this.instanceId,
|
|
86
|
+
app_version: this.appVersion,
|
|
87
|
+
client_name: this.clientInfo?.name,
|
|
88
|
+
client_version: this.clientInfo?.version,
|
|
89
|
+
tool: fields.tool,
|
|
90
|
+
reason: fields.reason,
|
|
91
|
+
node_version: process.version,
|
|
92
|
+
os: process.platform,
|
|
93
|
+
});
|
|
94
|
+
try {
|
|
95
|
+
await this.fetchImpl(ENDPOINT, {
|
|
96
|
+
method: "POST",
|
|
97
|
+
headers: { "Content-Type": "application/json" },
|
|
98
|
+
body,
|
|
99
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
// network failure, timeout abort or a synchronous throw — all silent
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Count every tool invocation by name. Wraps registerTool once, before the
|
|
109
|
+
* domain modules register their tools, so no per-tool wiring is needed.
|
|
110
|
+
* Only the tool *name* is recorded — arguments never reach telemetry.
|
|
111
|
+
*/
|
|
112
|
+
export function instrumentToolCalls(server, telemetry) {
|
|
113
|
+
const original = server.registerTool.bind(server);
|
|
114
|
+
// registerTool's generic signature does not survive a wrapper; the runtime
|
|
115
|
+
// shape (name, config, callback) is stable per SDK contract.
|
|
116
|
+
server.registerTool = ((name, config, callback) => original(name, config, ((...args) => {
|
|
117
|
+
telemetry.send("tool_call", { tool: name });
|
|
118
|
+
return callback(...args);
|
|
119
|
+
})));
|
|
120
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { contactFieldsShape, DESTRUCTIVE, fail, ok, personFieldsSchema, personResourceNameSchema, toContactFields, UPDATE, WRITE, } from "./util.js";
|
|
3
|
+
export function registerBatchTools(server, client) {
|
|
4
|
+
server.registerTool("batch_create_contacts", {
|
|
5
|
+
title: "Create many contacts at once",
|
|
6
|
+
annotations: WRITE,
|
|
7
|
+
description: "Creates up to 200 contacts in one call (People API people:batchCreateContacts). Each entry takes the same normalized fields as create_contact (name parts, emails[], phones[], addresses[], organization, birthday, notes, urls[]) and needs at least one. Returns createdPeople[] with each new resourceName. The call is atomic — a validation error anywhere creates nothing — but after an AMBIGUOUS failure (timeout/5xx; never auto-retried) the batch may still have committed: check via list_contacts before re-sending, or every contact gets created twice (the API has no duplicate detection). Send mutate batches sequentially, never in parallel — that is also how the per-user write quota stretches furthest.",
|
|
8
|
+
inputSchema: {
|
|
9
|
+
contacts: z
|
|
10
|
+
.array(z.object(contactFieldsShape()))
|
|
11
|
+
.min(1)
|
|
12
|
+
.max(200)
|
|
13
|
+
.describe("The contacts to create (1..200), each with the create_contact field set."),
|
|
14
|
+
read_mask: personFieldsSchema().optional(),
|
|
15
|
+
},
|
|
16
|
+
}, async ({ contacts, read_mask }) => {
|
|
17
|
+
try {
|
|
18
|
+
return ok(await client.batchCreateContacts(contacts.map((c) => toContactFields(c)), read_mask));
|
|
19
|
+
}
|
|
20
|
+
catch (e) {
|
|
21
|
+
return fail(e);
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
server.registerTool("batch_update_contacts", {
|
|
25
|
+
title: "Update many contacts at once",
|
|
26
|
+
annotations: UPDATE,
|
|
27
|
+
description: "Updates up to 200 contacts in one call (People API people:batchUpdateContacts). Each entry names a contact (resource_name, optional etag — missing etags are auto-fetched in ONE extra batchGet read) plus the same normalized fields as update_contact. CAUTION — the API applies ONE shared update mask to the whole batch, computed here as the union of every entry's provided field groups: a group that one entry provides and another omits is CLEARED on the omitting entry. Safest is to give every entry the same set of fields; each provided group replaces its stored group as a whole, exactly like update_contact. Atomic per request; a stale etag fails the whole batch with 400 — re-read and retry deliberately, never blindly.",
|
|
28
|
+
inputSchema: {
|
|
29
|
+
updates: z
|
|
30
|
+
.array(z.object({
|
|
31
|
+
resource_name: personResourceNameSchema(),
|
|
32
|
+
etag: z.string().optional().describe("The contact's current etag — omit to auto-fetch."),
|
|
33
|
+
...contactFieldsShape(),
|
|
34
|
+
}))
|
|
35
|
+
.min(1)
|
|
36
|
+
.max(200)
|
|
37
|
+
.describe("The updates (1..200) — give every entry the same set of contact fields (shared mask)."),
|
|
38
|
+
read_mask: personFieldsSchema().optional(),
|
|
39
|
+
},
|
|
40
|
+
}, async ({ updates, read_mask }) => {
|
|
41
|
+
try {
|
|
42
|
+
return ok(await client.batchUpdateContacts(updates.map((u) => ({
|
|
43
|
+
resourceName: u.resource_name,
|
|
44
|
+
etag: u.etag,
|
|
45
|
+
fields: toContactFields(u),
|
|
46
|
+
})), read_mask));
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
return fail(e);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
server.registerTool("batch_delete_contacts", {
|
|
53
|
+
title: "Delete many contacts at once",
|
|
54
|
+
annotations: DESTRUCTIVE,
|
|
55
|
+
description: "Permanently deletes up to 500 contacts in one call (People API people:batchDeleteContacts). There is no undo through this API — list the exact resource names first (batch_get_contacts shows what each one is) and treat the call as final. Returns an empty result on success; atomic per request. After an ambiguous failure (timeout/5xx; never auto-retried) check which contacts still exist via batch_get_contacts instead of re-sending — the deletes may have committed, and a second call then reports NOT_FOUND.",
|
|
56
|
+
inputSchema: {
|
|
57
|
+
resource_names: z
|
|
58
|
+
.array(personResourceNameSchema())
|
|
59
|
+
.min(1)
|
|
60
|
+
.max(500)
|
|
61
|
+
.describe("The contacts to delete permanently (1..500 people/<id> resource names)."),
|
|
62
|
+
},
|
|
63
|
+
}, async ({ resource_names }) => {
|
|
64
|
+
try {
|
|
65
|
+
return ok(await client.batchDeleteContacts(resource_names));
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
return fail(e);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { contactFieldsShape, DESTRUCTIVE, fail, ok, personFieldsSchema, personResourceNameSchema, READ_ONLY, toContactFields, UPDATE, WRITE, } from "./util.js";
|
|
3
|
+
export function registerContactTools(server, client) {
|
|
4
|
+
server.registerTool("list_contacts", {
|
|
5
|
+
title: "List contacts",
|
|
6
|
+
annotations: READ_ONLY,
|
|
7
|
+
description: "Lists the account's saved contacts (People API people/me/connections): connections[] of Person objects with resourceName, etag and the requested person_fields (default names, emailAddresses, phoneNumbers, organizations, memberships — an absent field may be unmasked, not empty), plus nextPageToken, totalItems and (when requested) nextSyncToken. page_size up to 1000 (default 100); paginate with page_token. For incremental polling set request_sync_token=true on a full listing, store nextSyncToken, and pass it as sync_token next time to get only changed/deleted people (deleted ones carry metadata.deleted=true); an expired token (~7 days) fails with HTTP 410 EXPIRED_SYNC_TOKEN — re-list without sync_token. Covers only the user's own saved contacts — not the Workspace directory and not auto-saved addresses (see list_other_contacts).",
|
|
8
|
+
inputSchema: {
|
|
9
|
+
person_fields: personFieldsSchema().optional(),
|
|
10
|
+
page_size: z.number().int().min(1).max(1000).optional().describe("Contacts per page (1..1000, default 100)."),
|
|
11
|
+
page_token: z.string().optional().describe("nextPageToken from the previous page."),
|
|
12
|
+
sort_order: z
|
|
13
|
+
.enum(["LAST_MODIFIED_ASCENDING", "LAST_MODIFIED_DESCENDING", "FIRST_NAME_ASCENDING", "LAST_NAME_ASCENDING"])
|
|
14
|
+
.optional()
|
|
15
|
+
.describe("Sort order (default LAST_MODIFIED_ASCENDING). Ignored when sync_token is set."),
|
|
16
|
+
request_sync_token: z
|
|
17
|
+
.boolean()
|
|
18
|
+
.optional()
|
|
19
|
+
.describe("Ask for a nextSyncToken on the last page (for later incremental syncs)."),
|
|
20
|
+
sync_token: z
|
|
21
|
+
.string()
|
|
22
|
+
.optional()
|
|
23
|
+
.describe("Sync token from a previous listing — returns only people changed since then."),
|
|
24
|
+
},
|
|
25
|
+
}, async ({ person_fields, page_size, page_token, sort_order, request_sync_token, sync_token }) => {
|
|
26
|
+
try {
|
|
27
|
+
return ok(await client.listContacts({
|
|
28
|
+
personFields: person_fields,
|
|
29
|
+
pageSize: page_size,
|
|
30
|
+
pageToken: page_token,
|
|
31
|
+
sortOrder: sort_order,
|
|
32
|
+
requestSyncToken: request_sync_token,
|
|
33
|
+
syncToken: sync_token,
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
return fail(e);
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
server.registerTool("search_contacts", {
|
|
41
|
+
title: "Search contacts",
|
|
42
|
+
annotations: READ_ONLY,
|
|
43
|
+
description: "Searches the account's saved contacts by prefix match on names, nicknames, emails, phones and organizations (People API people:searchContacts). Returns results[] of { person } with the requested read_mask fields. Max 30 results, no pagination — this is a quick lookup, not an export; use list_contacts to enumerate everything. The search index lags writes by seconds to minutes: a contact created or updated moments ago may be missing here even though list_contacts and get_contact already see it (the documented cache-warmup request is sent automatically before the session's first search, but the lag is server-side). Searches only the user's own saved contacts.",
|
|
44
|
+
inputSchema: {
|
|
45
|
+
query: z.string().min(1).describe('The search text, e.g. a name prefix ("Ann"), email or phone fragment.'),
|
|
46
|
+
read_mask: personFieldsSchema().optional(),
|
|
47
|
+
page_size: z.number().int().min(1).max(30).optional().describe("Max results (1..30, API cap; default 10)."),
|
|
48
|
+
},
|
|
49
|
+
}, async ({ query, read_mask, page_size }) => {
|
|
50
|
+
try {
|
|
51
|
+
return ok(await client.searchContacts({ query, readMask: read_mask, pageSize: page_size }));
|
|
52
|
+
}
|
|
53
|
+
catch (e) {
|
|
54
|
+
return fail(e);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
server.registerTool("get_contact", {
|
|
58
|
+
title: "Get a contact",
|
|
59
|
+
annotations: READ_ONLY,
|
|
60
|
+
description: 'Fetches one contact by resource name ("people/c...", or "people/me" for the signed-in user\'s own profile) with an explicit field mask. Returns a Person with resourceName, etag and the requested person_fields (default names, emailAddresses, phoneNumbers, organizations, memberships). The etag in the result is what update_contact needs to change this contact safely; memberships list the contact\'s groups as contactGroups/<id> resource names.',
|
|
61
|
+
inputSchema: {
|
|
62
|
+
resource_name: personResourceNameSchema(),
|
|
63
|
+
person_fields: personFieldsSchema().optional(),
|
|
64
|
+
},
|
|
65
|
+
}, async ({ resource_name, person_fields }) => {
|
|
66
|
+
try {
|
|
67
|
+
return ok(await client.getContact(resource_name, person_fields));
|
|
68
|
+
}
|
|
69
|
+
catch (e) {
|
|
70
|
+
return fail(e);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
server.registerTool("batch_get_contacts", {
|
|
74
|
+
title: "Get many contacts at once",
|
|
75
|
+
annotations: READ_ONLY,
|
|
76
|
+
description: "Fetches up to 200 contacts in one call (People API people:batchGet) — far cheaper against the tight per-user quota than a get_contact loop. Returns responses[], one per requested resource name IN THE SAME ORDER, each { requestedResourceName, status, person }; a missing contact gets a NOT_FOUND status in its own entry instead of failing the whole call, so check per-entry status. person_fields works exactly like in get_contact.",
|
|
77
|
+
inputSchema: {
|
|
78
|
+
resource_names: z
|
|
79
|
+
.array(personResourceNameSchema())
|
|
80
|
+
.min(1)
|
|
81
|
+
.max(200)
|
|
82
|
+
.describe("The contacts to fetch (1..200 people/<id> resource names)."),
|
|
83
|
+
person_fields: personFieldsSchema().optional(),
|
|
84
|
+
},
|
|
85
|
+
}, async ({ resource_names, person_fields }) => {
|
|
86
|
+
try {
|
|
87
|
+
return ok(await client.batchGetContacts(resource_names, person_fields));
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
return fail(e);
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
server.registerTool("create_contact", {
|
|
94
|
+
title: "Create a contact",
|
|
95
|
+
annotations: WRITE,
|
|
96
|
+
description: "Creates a new contact in the account's Google Contacts and returns the created Person (resourceName, etag and the person_fields mask — use the resourceName for every later call). Provide any subset of the normalized fields: name parts, nickname, emails[], phones[], addresses[], organization, birthday, notes, urls[]; at least one is required. The API has NO duplicate detection — creating the same contact twice yields two contacts, so after an ambiguous failure (timeout/5xx; never auto-retried) check via search/list before re-sending. A just-created contact appears in list_contacts/get_contact immediately but reaches the search_contacts index with a delay. Contact photos need raw_request (updateContactPhoto).",
|
|
97
|
+
inputSchema: {
|
|
98
|
+
...contactFieldsShape(),
|
|
99
|
+
person_fields: personFieldsSchema().optional(),
|
|
100
|
+
},
|
|
101
|
+
}, async (args) => {
|
|
102
|
+
try {
|
|
103
|
+
return ok(await client.createContact(toContactFields(args), args.person_fields));
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
return fail(e);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
server.registerTool("update_contact", {
|
|
110
|
+
title: "Update a contact",
|
|
111
|
+
annotations: UPDATE,
|
|
112
|
+
description: "Updates an existing contact and returns the updated Person. Only the provided fields are touched (updatePersonFields is computed automatically), but each provided field group is REPLACED AS A WHOLE: passing emails replaces all emails ([] clears them), passing any name part rewrites the whole name, and scalar fields clear on an empty value (\"\" for nickname/notes/birthday, {} for organization) — fetch current values with get_contact first and send complete groups, or data is silently dropped. Updates are etag-guarded: pass the etag from get_contact to fail cleanly (HTTP 400) if someone edited the contact meanwhile, or omit it and the current etag is fetched automatically (one extra read; last-write-wins). At least one contact field is required.",
|
|
113
|
+
inputSchema: {
|
|
114
|
+
resource_name: personResourceNameSchema(),
|
|
115
|
+
etag: z
|
|
116
|
+
.string()
|
|
117
|
+
.optional()
|
|
118
|
+
.describe("The contact's etag from get_contact — omit to auto-fetch the current one."),
|
|
119
|
+
...contactFieldsShape(),
|
|
120
|
+
person_fields: personFieldsSchema().optional(),
|
|
121
|
+
},
|
|
122
|
+
}, async (args) => {
|
|
123
|
+
try {
|
|
124
|
+
return ok(await client.updateContact({
|
|
125
|
+
resourceName: args.resource_name,
|
|
126
|
+
etag: args.etag,
|
|
127
|
+
fields: toContactFields(args),
|
|
128
|
+
personFields: args.person_fields,
|
|
129
|
+
}));
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
return fail(e);
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
server.registerTool("delete_contact", {
|
|
136
|
+
title: "Delete a contact",
|
|
137
|
+
annotations: DESTRUCTIVE,
|
|
138
|
+
description: "Permanently deletes one contact from the account's Google Contacts. There is no undo through this API (the Google Contacts UI keeps its own 30-day trash, but nothing here reads or restores it) — verify the resource_name with get_contact before deleting. Returns an empty result on success. After an ambiguous failure (timeout/5xx; never auto-retried) check with get_contact before re-sending: the delete may already have happened, and a second attempt then fails with 404.",
|
|
139
|
+
inputSchema: {
|
|
140
|
+
resource_name: personResourceNameSchema(),
|
|
141
|
+
},
|
|
142
|
+
}, async ({ resource_name }) => {
|
|
143
|
+
try {
|
|
144
|
+
return ok(await client.deleteContact(resource_name));
|
|
145
|
+
}
|
|
146
|
+
catch (e) {
|
|
147
|
+
return fail(e);
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { DESTRUCTIVE, fail, groupFieldsSchema, groupResourceNameSchema, ok, personResourceNameSchema, READ_ONLY, UPDATE, WRITE, } from "./util.js";
|
|
3
|
+
export function registerGroupTools(server, client) {
|
|
4
|
+
server.registerTool("list_contact_groups", {
|
|
5
|
+
title: "List contact groups",
|
|
6
|
+
annotations: READ_ONLY,
|
|
7
|
+
description: "Lists the account's contact groups (labels): contactGroups[] with resourceName (contactGroups/<id>), name, groupType and memberCount, plus nextPageToken and totalItems. Two kinds come back: USER_CONTACT_GROUP (labels the user created — the only kind that can be renamed or deleted) and SYSTEM_CONTACT_GROUP (built-ins like contactGroups/myContacts and contactGroups/starred — fixed). group_fields defaults to metadata, groupType, memberCount, name; add memberCount explicitly if you narrow it and still want sizes. page_size up to 1000; sync_token works like in list_contacts (410 = expired, re-list in full).",
|
|
8
|
+
inputSchema: {
|
|
9
|
+
page_size: z.number().int().min(1).max(1000).optional().describe("Groups per page (1..1000, default 30)."),
|
|
10
|
+
page_token: z.string().optional().describe("nextPageToken from the previous page."),
|
|
11
|
+
group_fields: groupFieldsSchema().optional(),
|
|
12
|
+
sync_token: z.string().optional().describe("Sync token from a previous listing — only changes since then."),
|
|
13
|
+
},
|
|
14
|
+
}, async ({ page_size, page_token, group_fields, sync_token }) => {
|
|
15
|
+
try {
|
|
16
|
+
return ok(await client.listContactGroups({
|
|
17
|
+
pageSize: page_size,
|
|
18
|
+
pageToken: page_token,
|
|
19
|
+
groupFields: group_fields,
|
|
20
|
+
syncToken: sync_token,
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
catch (e) {
|
|
24
|
+
return fail(e);
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
server.registerTool("get_contact_group", {
|
|
28
|
+
title: "Get a contact group",
|
|
29
|
+
annotations: READ_ONLY,
|
|
30
|
+
description: "Fetches one contact group by resource name: name, groupType, memberCount and etag — plus, when max_members > 0, memberResourceNames[] with up to that many member contacts as people/<id> resource names (the only way the API returns a group's members; feed them to batch_get_contacts for details). The etag is what update_contact_group uses to rename safely.",
|
|
31
|
+
inputSchema: {
|
|
32
|
+
resource_name: groupResourceNameSchema(),
|
|
33
|
+
max_members: z
|
|
34
|
+
.number()
|
|
35
|
+
.int()
|
|
36
|
+
.min(0)
|
|
37
|
+
.optional()
|
|
38
|
+
.describe("How many member resource names to include (0 or omitted = none, just the group)."),
|
|
39
|
+
group_fields: groupFieldsSchema().optional(),
|
|
40
|
+
},
|
|
41
|
+
}, async ({ resource_name, max_members, group_fields }) => {
|
|
42
|
+
try {
|
|
43
|
+
return ok(await client.getContactGroup(resource_name, { maxMembers: max_members, groupFields: group_fields }));
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
return fail(e);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
server.registerTool("create_contact_group", {
|
|
50
|
+
title: "Create a contact group",
|
|
51
|
+
annotations: WRITE,
|
|
52
|
+
description: "Creates a new user contact group (label) and returns it (resourceName contactGroups/<id>, name, etag). Group names must be unique — creating a duplicate name fails with 409 CONFLICT rather than making a second group. Put contacts into the new group with modify_group_members.",
|
|
53
|
+
inputSchema: {
|
|
54
|
+
name: z.string().min(1).describe("The group's display name (must be unique among the user's groups)."),
|
|
55
|
+
},
|
|
56
|
+
}, async ({ name }) => {
|
|
57
|
+
try {
|
|
58
|
+
return ok(await client.createContactGroup(name));
|
|
59
|
+
}
|
|
60
|
+
catch (e) {
|
|
61
|
+
return fail(e);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
server.registerTool("update_contact_group", {
|
|
65
|
+
title: "Rename a contact group",
|
|
66
|
+
annotations: UPDATE,
|
|
67
|
+
description: "Renames a user contact group (the only mutable group attribute). Etag-guarded like contact updates: pass etag from get_contact_group to fail cleanly on a concurrent edit, or omit it and the current etag is fetched automatically (one extra read). System groups (contactGroups/myContacts, starred, ...) cannot be renamed; the new name must stay unique (409 CONFLICT otherwise). Returns the updated group.",
|
|
68
|
+
inputSchema: {
|
|
69
|
+
resource_name: groupResourceNameSchema(),
|
|
70
|
+
name: z.string().min(1).describe("The new display name."),
|
|
71
|
+
etag: z
|
|
72
|
+
.string()
|
|
73
|
+
.optional()
|
|
74
|
+
.describe("The group's etag from get_contact_group — omit to auto-fetch the current one."),
|
|
75
|
+
},
|
|
76
|
+
}, async ({ resource_name, name, etag }) => {
|
|
77
|
+
try {
|
|
78
|
+
return ok(await client.updateContactGroup({ resourceName: resource_name, name, etag }));
|
|
79
|
+
}
|
|
80
|
+
catch (e) {
|
|
81
|
+
return fail(e);
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
server.registerTool("delete_contact_group", {
|
|
85
|
+
title: "Delete a contact group",
|
|
86
|
+
annotations: DESTRUCTIVE,
|
|
87
|
+
description: "Permanently deletes a user contact group (label). By default the member contacts SURVIVE — they only lose the label; delete_contacts=true also PERMANENTLY DELETES every contact in the group, so use it only when that is explicitly wanted (check the roster first via get_contact_group with max_members). System groups cannot be deleted. Returns an empty result on success; there is no undo through this API.",
|
|
88
|
+
inputSchema: {
|
|
89
|
+
resource_name: groupResourceNameSchema(),
|
|
90
|
+
delete_contacts: z
|
|
91
|
+
.boolean()
|
|
92
|
+
.optional()
|
|
93
|
+
.describe("Also permanently delete every member contact (default false — contacts just lose the label)."),
|
|
94
|
+
},
|
|
95
|
+
}, async ({ resource_name, delete_contacts }) => {
|
|
96
|
+
try {
|
|
97
|
+
return ok(await client.deleteContactGroup(resource_name, delete_contacts));
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
return fail(e);
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
server.registerTool("modify_group_members", {
|
|
104
|
+
title: "Add or remove group members",
|
|
105
|
+
annotations: UPDATE,
|
|
106
|
+
description: "Adds and/or removes contacts in a contact group (label) in one call — at least one of add/remove is required, together up to ~1000 names. Contacts are addressed by their people/<id> resource names. The HTTP 200 response is NOT a full success receipt — read it: notFoundResourceNames lists contacts that do not exist (their changes were skipped) and canNotRemoveLastContactGroupResourceNames lists contacts that could not leave their last group. Removing a contact from a group never deletes the contact, and re-running the same call converges. Contacts cannot be removed from contactGroups/myContacts this way.",
|
|
107
|
+
inputSchema: {
|
|
108
|
+
resource_name: groupResourceNameSchema(),
|
|
109
|
+
add: z.array(personResourceNameSchema()).optional().describe("Contacts to add to the group."),
|
|
110
|
+
remove: z.array(personResourceNameSchema()).optional().describe("Contacts to remove from the group."),
|
|
111
|
+
},
|
|
112
|
+
}, async ({ resource_name, add, remove }) => {
|
|
113
|
+
try {
|
|
114
|
+
if ((!add || add.length === 0) && (!remove || remove.length === 0)) {
|
|
115
|
+
return fail(new Error("At least one of add or remove (non-empty) is required."));
|
|
116
|
+
}
|
|
117
|
+
return ok(await client.modifyGroupMembers({ resourceName: resource_name, add, remove }));
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
return fail(e);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { copyMaskSchema, fail, ok, otherContactFieldsSchema, otherContactResourceNameSchema, personFieldsSchema, READ_ONLY, WRITE, } from "./util.js";
|
|
3
|
+
export function registerOtherContactTools(server, client) {
|
|
4
|
+
server.registerTool("list_other_contacts", {
|
|
5
|
+
title: "List or search Other contacts",
|
|
6
|
+
annotations: READ_ONLY,
|
|
7
|
+
description: "Lists 'Other contacts' — addresses Google auto-saved from the user's email interactions; they are NOT in the saved contact list and never appear in list_contacts/search_contacts. Give query to search them instead of listing (prefix match, max 30 results, no pagination — the warmup request is sent automatically before the session's first search); without query it lists with page_token pagination (page_size up to 1000) and optional sync tokens (request_sync_token/sync_token; expired ones fail with 410 — re-list in full). Only names, emailAddresses, phoneNumbers, photos and metadata exist here. Other contacts are read-only: to edit one, first make it a real contact with copy_other_contact. Requires the contacts.other.readonly OAuth scope — a 403 means the refresh token was minted without it.",
|
|
8
|
+
inputSchema: {
|
|
9
|
+
query: z.string().min(1).optional().describe("Search text; when set, page_token and sync tokens are invalid."),
|
|
10
|
+
read_mask: otherContactFieldsSchema().optional(),
|
|
11
|
+
page_size: z
|
|
12
|
+
.number()
|
|
13
|
+
.int()
|
|
14
|
+
.min(1)
|
|
15
|
+
.max(1000)
|
|
16
|
+
.optional()
|
|
17
|
+
.describe("Page size when listing (1..1000, default 100); max matches when searching (1..30)."),
|
|
18
|
+
page_token: z.string().optional().describe("nextPageToken from the previous page (listing only)."),
|
|
19
|
+
request_sync_token: z.boolean().optional().describe("Ask for a nextSyncToken (listing only)."),
|
|
20
|
+
sync_token: z.string().optional().describe("Return only changes since this token (listing only)."),
|
|
21
|
+
},
|
|
22
|
+
}, async ({ query, read_mask, page_size, page_token, request_sync_token, sync_token }) => {
|
|
23
|
+
try {
|
|
24
|
+
if (query !== undefined) {
|
|
25
|
+
if (page_token !== undefined || request_sync_token !== undefined || sync_token !== undefined) {
|
|
26
|
+
return fail(new Error("query cannot be combined with page_token or sync tokens — search has neither pagination nor sync."));
|
|
27
|
+
}
|
|
28
|
+
if (page_size !== undefined && page_size > 30) {
|
|
29
|
+
return fail(new Error("page_size must be 30 or less when searching."));
|
|
30
|
+
}
|
|
31
|
+
return ok(await client.searchOtherContacts({ query, readMask: read_mask, pageSize: page_size }));
|
|
32
|
+
}
|
|
33
|
+
return ok(await client.listOtherContacts({
|
|
34
|
+
readMask: read_mask,
|
|
35
|
+
pageSize: page_size,
|
|
36
|
+
pageToken: page_token,
|
|
37
|
+
requestSyncToken: request_sync_token,
|
|
38
|
+
syncToken: sync_token,
|
|
39
|
+
}));
|
|
40
|
+
}
|
|
41
|
+
catch (e) {
|
|
42
|
+
return fail(e);
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
server.registerTool("copy_other_contact", {
|
|
46
|
+
title: "Copy an Other contact into My Contacts",
|
|
47
|
+
annotations: WRITE,
|
|
48
|
+
description: "Copies an 'Other contact' (from list_other_contacts) into the user's saved contacts — the only write that exists for Other contacts. copy_mask picks which fields carry over (names, emailAddresses, phoneNumbers; default all three). Returns the NEW saved person — use its resourceName ('people/c...') for further edits; the original otherContacts entry remains. Copying the same entry twice creates duplicate saved contacts. Requires BOTH the contacts and contacts.other.readonly OAuth scopes.",
|
|
49
|
+
inputSchema: {
|
|
50
|
+
resource_name: otherContactResourceNameSchema(),
|
|
51
|
+
copy_mask: copyMaskSchema().optional(),
|
|
52
|
+
read_mask: personFieldsSchema().optional(),
|
|
53
|
+
},
|
|
54
|
+
}, async ({ resource_name, copy_mask, read_mask }) => {
|
|
55
|
+
try {
|
|
56
|
+
return ok(await client.copyOtherContact({ resourceName: resource_name, copyMask: copy_mask, readMask: read_mask }));
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
return fail(e);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|