mcp-google-tasks 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/dist/client.js ADDED
@@ -0,0 +1,333 @@
1
+ import { GoogleTasksError } from "./types.js";
2
+ import { CredentialsError } from "./config.js";
3
+ /** Google's OAuth2 token endpoint — refresh tokens are exchanged here. */
4
+ const TOKEN_URL = "https://oauth2.googleapis.com/token";
5
+ /** The task-lists collection lives under the authenticated user, not a path parameter. */
6
+ const LISTS_PATH = "tasks/v1/users/@me/lists";
7
+ /**
8
+ * Normalizes a due date to the RFC3339 timestamp the API expects. A bare
9
+ * YYYY-MM-DD becomes midnight UTC; a full timestamp passes through. The API
10
+ * stores only the date part either way — the time of day is discarded.
11
+ */
12
+ export function normalizeDueDate(due) {
13
+ return /^\d{4}-\d{2}-\d{2}$/.test(due) ? `${due}T00:00:00.000Z` : due;
14
+ }
15
+ export class GoogleTasksClient {
16
+ config;
17
+ base;
18
+ timeoutMs;
19
+ maxRetries;
20
+ retryBaseMs;
21
+ /** Cached access token from the refresh flow, with its expiry. */
22
+ cachedToken;
23
+ /** In-flight refresh, deduping concurrent token requests. */
24
+ refreshInFlight;
25
+ constructor(config) {
26
+ this.config = config;
27
+ this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
28
+ this.timeoutMs = config.timeoutMs ?? 60_000;
29
+ this.maxRetries = config.maxRetries ?? 3;
30
+ this.retryBaseMs = config.retryBaseMs ?? 500;
31
+ }
32
+ canRefresh() {
33
+ return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
34
+ }
35
+ /**
36
+ * Returns a valid Bearer token. With the refresh triple configured, mints an
37
+ * access token from the refresh token and caches it until shortly before it
38
+ * expires (concurrent callers share one in-flight refresh); otherwise the
39
+ * static GOOGLE_TASKS_ACCESS_TOKEN is used as-is. With neither configured,
40
+ * throws {@link CredentialsError} BEFORE any fetch — a missing setup must
41
+ * never enter the retry/backoff loop or trigger the 401 re-mint, because no
42
+ * amount of retrying mints credentials.
43
+ */
44
+ async accessToken(forceRefresh = false) {
45
+ if (!this.canRefresh()) {
46
+ if (!this.config.accessToken)
47
+ throw new CredentialsError();
48
+ return this.config.accessToken;
49
+ }
50
+ if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
51
+ return this.cachedToken.value;
52
+ }
53
+ if (!this.refreshInFlight) {
54
+ this.refreshInFlight = this.refreshAccessToken().finally(() => {
55
+ this.refreshInFlight = undefined;
56
+ });
57
+ }
58
+ return this.refreshInFlight;
59
+ }
60
+ /** Exchanges the refresh token for a fresh access token at Google's token endpoint. */
61
+ async refreshAccessToken() {
62
+ const body = new URLSearchParams({
63
+ client_id: this.config.clientId,
64
+ client_secret: this.config.clientSecret,
65
+ refresh_token: this.config.refreshToken,
66
+ grant_type: "refresh_token",
67
+ }).toString();
68
+ const { res, text } = await this.fetchWithTimeout(TOKEN_URL, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body }, "oauth2 token refresh");
69
+ let data;
70
+ try {
71
+ data = JSON.parse(text);
72
+ }
73
+ catch {
74
+ data = text;
75
+ }
76
+ if (!res.ok)
77
+ throw new GoogleTasksError(res.status, data);
78
+ const token = data.access_token;
79
+ if (typeof token !== "string" || !token) {
80
+ throw new Error("OAuth2 token endpoint returned no access_token.");
81
+ }
82
+ const expiresIn = Number(data.expires_in);
83
+ const ttl = Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600;
84
+ // Refresh 60s ahead of the real expiry so requests never race a dying token.
85
+ this.cachedToken = { value: token, expiresAt: Date.now() + Math.max(ttl - 60, 30) * 1000 };
86
+ return token;
87
+ }
88
+ /** Verifies the OAuth credentials by minting a fresh access token (refresh flow only). */
89
+ async authCheck() {
90
+ if (!this.canRefresh()) {
91
+ throw new Error("authCheck needs the refresh flow (GOOGLE_TASKS_CLIENT_ID / _CLIENT_SECRET / _REFRESH_TOKEN); with a static GOOGLE_TASKS_ACCESS_TOKEN list the task lists instead.");
92
+ }
93
+ await this.accessToken(true);
94
+ return { ok: true, auth: "refresh_token" };
95
+ }
96
+ /** Backoff before a retry: honors Retry-After when present, else exponential (capped at 30s). */
97
+ backoffMs(attempt, res) {
98
+ const retryAfter = res ? Number(res.headers.get("Retry-After")) : NaN;
99
+ if (Number.isFinite(retryAfter) && retryAfter > 0)
100
+ return Math.min(retryAfter, 30) * 1000;
101
+ return Math.min(this.retryBaseMs * 2 ** attempt, 30_000);
102
+ }
103
+ /**
104
+ * fetch with an AbortController timeout. Reads the response body inside the
105
+ * guarded zone so the timeout also covers a slow or drip-feeding body, not
106
+ * just the initial headers, and returns the text alongside the response.
107
+ */
108
+ async fetchWithTimeout(url, init, label) {
109
+ const controller = new AbortController();
110
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
111
+ try {
112
+ const res = await fetch(url, { ...init, signal: controller.signal });
113
+ const text = await res.text();
114
+ return { res, text };
115
+ }
116
+ catch (err) {
117
+ if (err instanceof Error && err.name === "AbortError") {
118
+ throw new Error(`Request to "${label}" timed out after ${this.timeoutMs}ms`);
119
+ }
120
+ throw err;
121
+ }
122
+ finally {
123
+ clearTimeout(timer);
124
+ }
125
+ }
126
+ /**
127
+ * Low-level request to a Google Tasks API path (e.g. "tasks/v1/users/@me/lists").
128
+ * Auth is a Bearer token (refreshed transparently; a 401 forces one re-mint +
129
+ * retry). 429 is always retried with backoff; 5xx and network errors/timeouts
130
+ * are retried only for GET — the Tasks API has real writes, and replaying a
131
+ * write after an ambiguous failure could duplicate the task or repeat the
132
+ * delete against a shifted target. Any other non-2xx throws a
133
+ * {@link GoogleTasksError}.
134
+ */
135
+ async request(method, path, body, query) {
136
+ // Guard method !== "GET" keeps undici from crashing on a GET-with-body.
137
+ const hasBody = body !== undefined && method !== "GET";
138
+ // Resolve the path against the API base, then reject anything that escaped
139
+ // to a foreign origin (an absolute "https://evil/x" or a "\\evil/x" slipped
140
+ // through raw_request) so the Bearer token can never leak to another host.
141
+ const url = new URL(path.replace(/^\//, ""), this.base);
142
+ if (url.origin !== new URL(this.base).origin) {
143
+ throw new Error(`raw_request path must be a relative API path (resolved to foreign origin ${url.origin})`);
144
+ }
145
+ if (query) {
146
+ for (const [key, value] of Object.entries(query)) {
147
+ if (value !== undefined)
148
+ url.searchParams.set(key, String(value));
149
+ }
150
+ }
151
+ const target = url.toString();
152
+ // Writes must not be replayed on ambiguous failures (see the retry gate below).
153
+ const idempotent = method === "GET";
154
+ let refreshedOn401 = false;
155
+ for (let attempt = 0;; attempt++) {
156
+ const token = await this.accessToken();
157
+ const headers = { Authorization: `Bearer ${token}` };
158
+ if (hasBody)
159
+ headers["Content-Type"] = "application/json";
160
+ let res;
161
+ let text;
162
+ try {
163
+ ({ res, text } = await this.fetchWithTimeout(target, { method, headers, body: hasBody ? JSON.stringify(body) : undefined }, path));
164
+ }
165
+ catch (err) {
166
+ // Network error or timeout: the request may or may not have reached the
167
+ // API, so only reads are retried; writes rethrow immediately.
168
+ if (idempotent && attempt < this.maxRetries) {
169
+ await delay(this.backoffMs(attempt));
170
+ continue;
171
+ }
172
+ throw err;
173
+ }
174
+ // An expired/revoked access token: re-mint once and replay. The request
175
+ // never executed, so this is safe for writes too.
176
+ if (res.status === 401 && this.canRefresh() && !refreshedOn401) {
177
+ refreshedOn401 = true;
178
+ await this.accessToken(true);
179
+ continue;
180
+ }
181
+ // 429 means the request was rejected before executing — safe to retry for
182
+ // any method. 5xx is ambiguous (the write may have committed), so it is
183
+ // gated to idempotent requests.
184
+ const transient = res.status === 429 || (idempotent && res.status >= 500 && res.status < 600);
185
+ if (transient && attempt < this.maxRetries) {
186
+ await delay(this.backoffMs(attempt, res));
187
+ continue;
188
+ }
189
+ let data = undefined;
190
+ if (text) {
191
+ try {
192
+ data = JSON.parse(text);
193
+ }
194
+ catch {
195
+ data = text;
196
+ }
197
+ }
198
+ if (!res.ok)
199
+ throw new GoogleTasksError(res.status, data);
200
+ return data;
201
+ }
202
+ }
203
+ // ---- Task lists ----
204
+ /** Lists the user's task lists (paginated; the API defaults to and caps a page at 1000). */
205
+ async listTaskLists(p = {}) {
206
+ return this.request("GET", LISTS_PATH, undefined, {
207
+ maxResults: p.pageSize,
208
+ pageToken: p.pageToken,
209
+ });
210
+ }
211
+ /** One task list by id (or the "@default" alias). */
212
+ async getTaskList(taskListId) {
213
+ return this.request("GET", `${LISTS_PATH}/${encodeURIComponent(taskListId)}`);
214
+ }
215
+ /** Creates a task list. The API accepts only a title. */
216
+ async createTaskList(title) {
217
+ return this.request("POST", LISTS_PATH, { title });
218
+ }
219
+ /** Renames a task list (PATCH — the title is the only writable field). */
220
+ async updateTaskList(taskListId, title) {
221
+ return this.request("PATCH", `${LISTS_PATH}/${encodeURIComponent(taskListId)}`, { title });
222
+ }
223
+ /** Deletes a task list AND every task in it. The default list cannot be deleted. */
224
+ async deleteTaskList(taskListId) {
225
+ const data = await this.request("DELETE", `${LISTS_PATH}/${encodeURIComponent(taskListId)}`);
226
+ // The API answers 204 with an empty body; return an explicit confirmation
227
+ // (echoing the target) instead of null so the calling model knows exactly
228
+ // which delete went through.
229
+ return data ?? { deleted: true, tasklist_id: taskListId };
230
+ }
231
+ // ---- Tasks ----
232
+ tasksPath(taskListId, taskId) {
233
+ const base = `tasks/v1/lists/${encodeURIComponent(taskListId)}/tasks`;
234
+ return taskId === undefined ? base : `${base}/${encodeURIComponent(taskId)}`;
235
+ }
236
+ /**
237
+ * Lists tasks with the API's filters mapped from the normalized vocabulary
238
+ * (updated_min → updatedMin, due_max → dueMax, page_size → maxResults, ...).
239
+ * Booleans are forwarded only when set so the API defaults stay in charge.
240
+ */
241
+ async listTasks(p) {
242
+ return this.request("GET", this.tasksPath(p.taskListId), undefined, {
243
+ updatedMin: p.updatedMin,
244
+ dueMin: p.dueMin,
245
+ dueMax: p.dueMax,
246
+ completedMin: p.completedMin,
247
+ completedMax: p.completedMax,
248
+ showCompleted: p.showCompleted,
249
+ showHidden: p.showHidden,
250
+ showDeleted: p.showDeleted,
251
+ showAssigned: p.showAssigned,
252
+ maxResults: p.pageSize,
253
+ pageToken: p.pageToken,
254
+ });
255
+ }
256
+ /** One task by id. */
257
+ async getTask(taskListId, taskId) {
258
+ return this.request("GET", this.tasksPath(taskListId, taskId));
259
+ }
260
+ /**
261
+ * Creates a task. Position and hierarchy are query parameters, not body
262
+ * fields: parent makes it a subtask, previous places it after a sibling
263
+ * (both omitted = top of the list). The due date is normalized to RFC3339.
264
+ */
265
+ async createTask(p) {
266
+ return this.request("POST", this.tasksPath(p.taskListId), compact({
267
+ title: p.title,
268
+ notes: p.notes,
269
+ due: p.due === undefined ? undefined : normalizeDueDate(p.due),
270
+ }), { parent: p.parent, previous: p.previous });
271
+ }
272
+ /**
273
+ * Patches title / notes / due. Only the provided fields change; clearDue and
274
+ * clearNotes send an explicit null, which is how PATCH erases a field. The
275
+ * parent and the position cannot be changed here — that is moveTask's job —
276
+ * and the completion status is setTaskStatus's.
277
+ */
278
+ async updateTask(p) {
279
+ const body = compact({
280
+ title: p.title,
281
+ notes: p.clearNotes ? null : p.notes,
282
+ due: p.clearDue ? null : p.due === undefined ? undefined : normalizeDueDate(p.due),
283
+ });
284
+ if (Object.keys(body).length === 0) {
285
+ throw new Error("At least one of title, notes, due, clear_due or clear_notes is required.");
286
+ }
287
+ return this.request("PATCH", this.tasksPath(p.taskListId, p.taskId), body);
288
+ }
289
+ /**
290
+ * Moves a task: to another parent (or the top level), after another sibling
291
+ * (or to the first position), and/or to another task list. Everything is a
292
+ * query parameter — the move endpoint takes no body.
293
+ */
294
+ async moveTask(p) {
295
+ return this.request("POST", `${this.tasksPath(p.taskListId, p.taskId)}/move`, {}, {
296
+ parent: p.parent,
297
+ previous: p.previous,
298
+ destinationTasklist: p.destinationTasklist,
299
+ });
300
+ }
301
+ /** Deletes a task permanently (it stays visible to list_tasks show_deleted for a while, for sync). */
302
+ async deleteTask(taskListId, taskId) {
303
+ const data = await this.request("DELETE", this.tasksPath(taskListId, taskId));
304
+ return data ?? { deleted: true, tasklist_id: taskListId, task_id: taskId };
305
+ }
306
+ /**
307
+ * Flips the completion status. Completing sets status=completed (the API
308
+ * stamps the completion time); reopening sets status=needsAction and
309
+ * explicitly nulls the completed timestamp. Both directions are reversible —
310
+ * this is the safe counterpart to deleteTask.
311
+ */
312
+ async setTaskStatus(taskListId, taskId, completed) {
313
+ const body = completed
314
+ ? { status: "completed" }
315
+ : { status: "needsAction", completed: null };
316
+ return this.request("PATCH", this.tasksPath(taskListId, taskId), body);
317
+ }
318
+ /**
319
+ * Clears completed tasks from a list: they are flagged hidden and stop
320
+ * showing up by default (list_tasks still finds them with show_hidden).
321
+ */
322
+ async clearCompletedTasks(taskListId) {
323
+ const data = await this.request("POST", `tasks/v1/lists/${encodeURIComponent(taskListId)}/clear`, {});
324
+ return data ?? { cleared: true, tasklist_id: taskListId };
325
+ }
326
+ }
327
+ /** Drops keys whose value is `undefined` so they are not sent to the API (null survives — it clears). */
328
+ function compact(obj) {
329
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
330
+ }
331
+ function delay(ms) {
332
+ return new Promise((resolve) => setTimeout(resolve, ms));
333
+ }
package/dist/config.js ADDED
@@ -0,0 +1,83 @@
1
+ /** Default Google Tasks API host. */
2
+ export const DEFAULT_BASE = "https://tasks.googleapis.com";
3
+ /**
4
+ * A malformed environment variable. Thrown instead of exiting on the spot so
5
+ * index.ts can catch it, report the drop-off and start degraded instead of
6
+ * dying; `reason` is the machine-readable code that ships with that ping
7
+ * (never a variable's value).
8
+ */
9
+ export class ConfigError extends Error {
10
+ reason;
11
+ constructor(message, reason) {
12
+ super(message);
13
+ this.name = "ConfigError";
14
+ this.reason = reason;
15
+ }
16
+ }
17
+ /**
18
+ * What a tool call without credentials reads. The first sentence is the
19
+ * historical startup error, verbatim — the rest exists because credentials come
20
+ * only from the environment, so the fix is an operator action plus a restart,
21
+ * never a retry.
22
+ */
23
+ export const MISSING_CREDENTIALS_MESSAGE = "Google OAuth credentials are required: set GOOGLE_TASKS_CLIENT_ID + " +
24
+ "GOOGLE_TASKS_CLIENT_SECRET + GOOGLE_TASKS_REFRESH_TOKEN (recommended), or " +
25
+ "GOOGLE_TASKS_ACCESS_TOKEN with a short-lived access token. " +
26
+ "This is not a network failure and retrying will not help: the operator must set these " +
27
+ "environment variables in the MCP client's server config and restart the server — they are " +
28
+ "read only at startup.";
29
+ /**
30
+ * Raised when a tool call needs credentials and none were configured. The
31
+ * message is the whole point of the class: it is the only text the calling
32
+ * model reads about the missing setup, so it names the fix (which variables,
33
+ * and that a restart is needed) instead of the failure.
34
+ */
35
+ export class CredentialsError extends Error {
36
+ constructor(message = MISSING_CREDENTIALS_MESSAGE) {
37
+ super(message);
38
+ this.name = "CredentialsError";
39
+ }
40
+ }
41
+ /** True when the config carries usable credentials (the full refresh triple or a static token). */
42
+ export function hasCredentials(config) {
43
+ return Boolean(config.accessToken || (config.clientId && config.clientSecret && config.refreshToken));
44
+ }
45
+ /**
46
+ * Builds the client config from environment variables.
47
+ *
48
+ * Missing credentials are NOT an error here: the server starts anyway and the
49
+ * client raises {@link CredentialsError} on the first tool call, so an
50
+ * unconfigured install completes the MCP handshake and carries the fix into
51
+ * the session instead of dying before it with nothing to read. A malformed
52
+ * setup — the refresh triple set only partially — still throws, because
53
+ * guessing what the user meant is worse.
54
+ *
55
+ * GOOGLE_TASKS_CLIENT_ID OAuth2 client id (refresh flow, recommended)
56
+ * GOOGLE_TASKS_CLIENT_SECRET OAuth2 client secret (refresh flow)
57
+ * GOOGLE_TASKS_REFRESH_TOKEN OAuth2 refresh token (refresh flow)
58
+ * GOOGLE_TASKS_ACCESS_TOKEN static access token (alternative; expires in ~1h)
59
+ * GOOGLE_TASKS_API_BASE API root override (default https://tasks.googleapis.com)
60
+ * GOOGLE_TASKS_TIMEOUT_MS per-request timeout (default 60000)
61
+ * GOOGLE_TASKS_MAX_RETRIES retries on transient errors (default 3)
62
+ */
63
+ export function loadConfig() {
64
+ const clientId = process.env.GOOGLE_TASKS_CLIENT_ID;
65
+ const clientSecret = process.env.GOOGLE_TASKS_CLIENT_SECRET;
66
+ const refreshToken = process.env.GOOGLE_TASKS_REFRESH_TOKEN;
67
+ const accessToken = process.env.GOOGLE_TASKS_ACCESS_TOKEN;
68
+ const oauthProvided = [clientId, clientSecret, refreshToken].filter(Boolean).length;
69
+ if (oauthProvided > 0 && oauthProvided < 3) {
70
+ throw new ConfigError("GOOGLE_TASKS_CLIENT_ID, GOOGLE_TASKS_CLIENT_SECRET and GOOGLE_TASKS_REFRESH_TOKEN must be set together (OAuth2 refresh flow).", "incomplete_oauth_config");
71
+ }
72
+ const timeoutMs = Number(process.env.GOOGLE_TASKS_TIMEOUT_MS);
73
+ const maxRetries = Number(process.env.GOOGLE_TASKS_MAX_RETRIES);
74
+ return {
75
+ clientId,
76
+ clientSecret,
77
+ refreshToken,
78
+ accessToken,
79
+ apiBase: process.env.GOOGLE_TASKS_API_BASE || DEFAULT_BASE,
80
+ timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 60_000,
81
+ maxRetries: Number.isFinite(maxRetries) && maxRetries >= 0 ? maxRetries : 3,
82
+ };
83
+ }
package/dist/index.js ADDED
@@ -0,0 +1,119 @@
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 { GoogleTasksClient } from "./client.js";
6
+ import { ConfigError, DEFAULT_BASE, hasCredentials, loadConfig } from "./config.js";
7
+ import { instrumentToolCalls, Telemetry } from "./telemetry.js";
8
+ import { registerTaskListTools } from "./tools/tasklists.js";
9
+ import { registerTaskTools } from "./tools/tasks.js";
10
+ import { registerCompletionTools } from "./tools/completion.js";
11
+ import { registerRawTool } from "./tools/raw.js";
12
+ /**
13
+ * Prose handed to the calling model in the `initialize` result — the only place
14
+ * it learns what the tool list cannot say: which Google product this API is,
15
+ * what the API refuses to do, and the behaviours that make a naive loop
16
+ * expensive, lossy or duplicating.
17
+ */
18
+ const INSTRUCTIONS = "Google Tasks API v1 manages the user's Google Tasks lists — not Calendar events, Keep notes or " +
19
+ "Reminders. Due dates are DATES only: any time of day sent is discarded and never returned; " +
20
+ "recurrence is invisible to the API entirely. Completing is not deleting: complete_task is " +
21
+ "reversible via reopen_task, while delete_task and delete_tasklist are permanent (delete_tasklist " +
22
+ "takes every task in the list with it; the default list cannot be deleted). Tasks completed in " +
23
+ "Google's own apps are flagged hidden — list them with show_completed=true AND show_hidden=true. " +
24
+ "Hierarchy is parent/previous at create_task or move_task only (parent and position are read-only " +
25
+ "fields; positions are opaque strings — sort by them, never fabricate them); one nesting level is " +
26
+ "what Google's UI supports. There are no push notifications: sync by polling list_tasks with " +
27
+ "updated_min plus show_deleted/show_hidden. Task pages cap at 100 items (default 20; task-list " +
28
+ "pages at 1000), the API has no text search — filter client-side — and the project quota is a " +
29
+ "courtesy 50,000 queries/day, so poll incrementally. Writes hit live data and are never retried after a 5xx or " +
30
+ "timeout: verify with get_task before re-sending; clear_completed_tasks hides a whole list's " +
31
+ "completed tasks at once. Auth that suddenly breaks usually means the OAuth consent screen is " +
32
+ "still in Testing, where refresh tokens die after 7 days.";
33
+ /**
34
+ * Prepended to INSTRUCTIONS when no credentials are configured. The model reads
35
+ * this before it picks a tool, so an unconfigured session opens with the fix
36
+ * rather than with a failed call. There is no in-chat login here: credentials
37
+ * come only from the environment, so the fix is an operator action + restart.
38
+ */
39
+ const UNCONFIGURED_PREFIX = "ATTENTION: Google Tasks is not connected yet — no credentials are configured, so every " +
40
+ "tool call will fail. The operator must set GOOGLE_TASKS_CLIENT_ID + " +
41
+ "GOOGLE_TASKS_CLIENT_SECRET + GOOGLE_TASKS_REFRESH_TOKEN (recommended), or " +
42
+ "GOOGLE_TASKS_ACCESS_TOKEN with a short-lived access token, in the MCP client's " +
43
+ "server config and restart this server — the variables are read only at startup. ";
44
+ /** Reads the package version so the server reports its real version to MCP clients. */
45
+ function readVersion() {
46
+ try {
47
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
48
+ return typeof pkg.version === "string" ? pkg.version : "0.0.0";
49
+ }
50
+ catch {
51
+ return "0.0.0";
52
+ }
53
+ }
54
+ /**
55
+ * Loads the config without dying on a bad value. A server that exits here never
56
+ * completes the MCP handshake, so the user sees a dead server and no reason.
57
+ * Instead the problem is carried into the session, where the model can read it
58
+ * and relay it: the config degrades to "no credentials" and every tool call
59
+ * fails with the actionable message.
60
+ */
61
+ function loadConfigOrDegraded(telemetry) {
62
+ try {
63
+ return { config: loadConfig() };
64
+ }
65
+ catch (err) {
66
+ if (!(err instanceof ConfigError))
67
+ throw err;
68
+ console.error(`Error: ${err.message}`);
69
+ // Fire-and-forget now that the process survives: the historical
70
+ // `startup_failed` funnel stays comparable, but nothing blocks startup.
71
+ telemetry.send("startup_failed", { reason: err.reason });
72
+ return {
73
+ config: { apiBase: process.env.GOOGLE_TASKS_API_BASE || DEFAULT_BASE },
74
+ problem: err,
75
+ };
76
+ }
77
+ }
78
+ async function main() {
79
+ // Anonymous usage pings (ids/names/versions only, never data or arguments);
80
+ // opt out with ASKADS_TELEMETRY=0. Built before the config so missing
81
+ // credentials can be reported; wired to the server before tools register.
82
+ const telemetry = new Telemetry(readVersion());
83
+ const { config, problem } = loadConfigOrDegraded(telemetry);
84
+ const client = new GoogleTasksClient(config);
85
+ // Decided once, at startup: credentials come only from the environment, so
86
+ // "restart after setting the variables" is the accurate advice to give.
87
+ const connected = hasCredentials(config);
88
+ const server = new McpServer({
89
+ name: "mcp-google-tasks",
90
+ version: readVersion(),
91
+ },
92
+ // Surfaces in the initialize result, before the client sees a single tool.
93
+ {
94
+ instructions: connected
95
+ ? INSTRUCTIONS
96
+ : UNCONFIGURED_PREFIX + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
97
+ });
98
+ instrumentToolCalls(server, telemetry);
99
+ server.server.oninitialized = () => {
100
+ telemetry.setClientInfo(server.server.getClientVersion());
101
+ // Split on purpose: `server_start` keeps meaning "a usable install started",
102
+ // so the unconfigured case gets its own event instead of inflating that number.
103
+ if (connected)
104
+ telemetry.send("server_start");
105
+ else
106
+ telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
107
+ };
108
+ registerTaskListTools(server, client);
109
+ registerTaskTools(server, client);
110
+ registerCompletionTools(server, client);
111
+ registerRawTool(server, client);
112
+ const transport = new StdioServerTransport();
113
+ await server.connect(transport);
114
+ console.error(`mcp-google-tasks running on stdio${connected ? "" : " (no credentials — set the environment variables and restart)"}`);
115
+ }
116
+ main().catch((err) => {
117
+ console.error("Fatal error starting mcp-google-tasks:", err);
118
+ process.exit(1);
119
+ });
@@ -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, task
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-tasks";
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
+ }