copilot-agents-mcp 0.0.1 → 0.2.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/cli.js CHANGED
@@ -1,20 +1,26 @@
1
1
  #!/usr/bin/env node
2
2
  import { realpathSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
3
4
  import { resolve } from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
7
  import { authLockPath, createAppSession, createMemoryStore, githubAppClientId, ignoredTokenWarning, loginWithDeviceFlow, logoutLocal, logoutMessage, personalAccessToken, readActiveToken, readGitHubApp, statusReport, systemAccount, } from "./auth.js";
7
8
  import { createGitHubClient } from "./github.js";
8
- import { startHttpServer } from "./http.js";
9
9
  import { NO_SESSION_MESSAGE, ToolFailure } from "./errors.js";
10
10
  import { readSweModels } from "./swe-models.js";
11
- import { assertSelection, splitList } from "./selection.js";
12
11
  import { buildServer, defaultLaunchWatcher, packageVersion } from "./server.js";
12
+ import { buildLocalStatusDiagnostics } from "./status-local.js";
13
13
  import { defaultStatePath } from "./state.js";
14
- import { deliverNotice } from "./notify.js";
14
+ import { deliverTaskNotice } from "./notify.js";
15
15
  import { acquireWatcher, releaseWatcher, runWatcher, watcherLockPath } from "./watch.js";
16
- export function parseArgs(argv, env) {
16
+ import { listWebhooks, registerWebhook, removeWebhook, WEBHOOK_ERROR, WEBHOOK_INPUT_ERROR } from "./webhooks.js";
17
+ import { validateOwner } from "./tasks.js";
18
+ import { WebhookValidationError } from "./webhook-http.js";
19
+ export const WATCH_POLL_INTERVAL_MS = 15_000;
20
+ export function parseArgs(argv) {
17
21
  const args = [...argv];
22
+ if (args[0] === "webhook")
23
+ return parseWebhookArgs(args.slice(1));
18
24
  if (args.includes("--version"))
19
25
  return { command: "version" };
20
26
  if (args[0] === "watch") {
@@ -37,87 +43,44 @@ export function parseArgs(argv, env) {
37
43
  throw new Error("Use `auth status`.");
38
44
  return { command: "status" };
39
45
  }
40
- let http = false;
41
- let port;
42
- let toolsets;
43
- let tools;
44
- let exclude;
45
- let readOnly = false;
46
- let features;
47
46
  for (let index = 0; index < args.length; index += 1) {
48
47
  const arg = args[index];
49
48
  if (!arg)
50
49
  continue;
51
50
  if (arg === "--help" || arg === "-h")
52
51
  throw new Help();
53
- if (arg === "--http") {
54
- http = true;
55
- continue;
56
- }
57
- if (arg === "--read-only") {
58
- readOnly = true;
59
- continue;
60
- }
61
- const value = valueOf(arg, args, index);
62
- if (value.consumed)
63
- index += 1;
64
- if (value.name === "--port") {
65
- port = Number(value.text);
66
- if (!Number.isInteger(port) || port < 0 || port > 65535)
67
- throw new Error("--port must be an integer from 0 to 65535.");
68
- continue;
69
- }
70
- if (value.name === "--toolsets") {
71
- toolsets = splitList(value.text);
72
- continue;
73
- }
74
- if (value.name === "--tools") {
75
- tools = splitList(value.text);
76
- continue;
77
- }
78
- if (value.name === "--exclude-tools") {
79
- exclude = splitList(value.text);
80
- continue;
81
- }
82
- if (value.name === "--features") {
83
- features = splitList(value.text);
84
- continue;
85
- }
86
- throw new Error(`Unknown argument: ${arg}`);
52
+ throw new Error("Unknown argument.");
87
53
  }
88
- const selection = {
89
- exclude: exclude ?? (env.GITHUB_EXCLUDE_TOOLS ? splitList(env.GITHUB_EXCLUDE_TOOLS) : []),
90
- readOnly: readOnly || /^(1|true)$/i.test(env.GITHUB_READ_ONLY ?? ""),
91
- features: features ?? [],
92
- };
93
- if (toolsets)
94
- selection.toolsets = toolsets;
95
- else if (env.GITHUB_TOOLSETS)
96
- selection.toolsets = splitList(env.GITHUB_TOOLSETS);
97
- if (tools)
98
- selection.tools = tools;
99
- else if (env.GITHUB_TOOLS)
100
- selection.tools = splitList(env.GITHUB_TOOLS);
101
- assertSelection(selection);
102
- if (http)
103
- return { command: "serve", http: true, port: port ?? 3333, selection };
104
- if (port !== undefined)
105
- throw new Error("--port can only be used with --http.");
106
- return { command: "serve", http: false, selection };
54
+ return { command: "serve" };
107
55
  }
108
- function valueOf(arg, args, index) {
109
- const names = ["--port", "--toolsets", "--tools", "--exclude-tools", "--features"];
110
- for (const name of names) {
111
- if (arg === name) {
112
- const text = args[index + 1];
113
- if (!text || text.startsWith("--"))
114
- throw new Error(`Missing value for ${name}.`);
115
- return { name, text, consumed: true };
56
+ function parseWebhookArgs(args) {
57
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h"))
58
+ throw new Help();
59
+ const action = args[0];
60
+ if ((action === "register" || action === "remove" || action === "list") && args.length === 2 && (args[1] === "--help" || args[1] === "-h")) {
61
+ throw new Help();
62
+ }
63
+ if (action === "list" && args.length === 1)
64
+ return { command: "webhook", action };
65
+ if (action !== "register" && action !== "remove")
66
+ throw new Error(WEBHOOK_INPUT_ERROR);
67
+ const values = new Map();
68
+ for (let index = 1; index < args.length; index += 2) {
69
+ const flag = args[index];
70
+ const value = args[index + 1];
71
+ if (!flag || !value || value.startsWith("-") || values.has(flag)
72
+ || (flag !== "--owner" && !(action === "register" && (flag === "--url-file" || flag === "--auth-file")))) {
73
+ throw new Error(WEBHOOK_INPUT_ERROR);
116
74
  }
117
- if (arg.startsWith(`${name}=`))
118
- return { name, text: arg.slice(name.length + 1), consumed: false };
75
+ values.set(flag, value);
76
+ }
77
+ try {
78
+ const owner = validateOwner(values.get("--owner") ?? "");
79
+ return { command: "webhook", action, owner, urlFile: values.get("--url-file"), authFile: values.get("--auth-file") };
80
+ }
81
+ catch {
82
+ throw new Error(WEBHOOK_INPUT_ERROR);
119
83
  }
120
- return { name: undefined, text: "", consumed: false };
121
84
  }
122
85
  class Help extends Error {
123
86
  constructor() {
@@ -131,8 +94,6 @@ function helpText() {
131
94
  " MCP server over stdio.",
132
95
  "copilot-agents-mcp --version",
133
96
  " Print the version from package.json.",
134
- "copilot-agents-mcp --http [--port 3333]",
135
- " MCP server over HTTP on 127.0.0.1.",
136
97
  "copilot-agents-mcp watch",
137
98
  " Watch pending tasks and notify once when they finish.",
138
99
  "copilot-agents-mcp login",
@@ -140,16 +101,39 @@ function helpText() {
140
101
  "copilot-agents-mcp logout",
141
102
  " Delete the keyring session.",
142
103
  "copilot-agents-mcp auth status",
143
- " Show which credential is active without showing the token.",
104
+ " Show which credential is active without showing the token, plus local diagnostics (state, notify env, D-Bus).",
105
+ "copilot-agents-mcp webhook register --owner <id> [--url-file <path>] [--auth-file <path>]",
106
+ " Files contain the URL and complete Authorization header value; surrounding whitespace is trimmed.",
107
+ " Missing secret files require hidden terminal prompts. Secrets are never accepted as arguments.",
108
+ "copilot-agents-mcp webhook list",
109
+ " Show owner, host, key file path, and registration time (never URL or authorization).",
110
+ "copilot-agents-mcp webhook remove --owner <id>",
111
+ " Remove the registration and key file; safe to repeat.",
144
112
  "",
145
- "Options: --toolsets, --tools, --exclude-tools, --read-only, --features",
146
113
  "Environment: GITHUB_PERSONAL_ACCESS_TOKEN, COPILOT_AGENTS_GITHUB_APP_CLIENT_ID,",
147
- "GITHUB_TOOLSETS, GITHUB_TOOLS, GITHUB_EXCLUDE_TOOLS, GITHUB_READ_ONLY,",
148
- "COPILOT_AGENTS_NOTIFY_URL, COPILOT_AGENTS_NOTIFY_AUTHORIZATION, COPILOT_AGENTS_STATE_PATH",
114
+ "COPILOT_AGENTS_NOTIFY_URL, COPILOT_AGENTS_NOTIFY_AUTHORIZATION, COPILOT_AGENTS_NOTIFY_ALLOWED_HOSTS,",
115
+ "COPILOT_AGENTS_STATE_PATH,",
116
+ "COPILOT_AGENTS_GITHUB_API_BASE_URL",
149
117
  ].join("\n");
150
118
  }
151
- async function serve(command) {
119
+ import { githubApiBase } from "./github-hosts.js";
120
+ export { githubApiBase };
121
+ export function warnGithubApiBase(env) {
122
+ const base = githubApiBase(env);
123
+ if (base)
124
+ console.error(`Using COPILOT_AGENTS_GITHUB_API_BASE_URL=${base}`);
125
+ }
126
+ function githubClient(token, env, session) {
127
+ const baseUrl = githubApiBase(env);
128
+ return createGitHubClient({
129
+ token,
130
+ tokens: session ?? undefined,
131
+ ...(baseUrl ? { baseUrl } : {}),
132
+ });
133
+ }
134
+ async function serve() {
152
135
  warnIgnored(process.env);
136
+ warnGithubApiBase(process.env);
153
137
  const statePath = defaultStatePath();
154
138
  const pat = personalAccessToken(process.env);
155
139
  const session = pat ? null : await openAppSession(process.env, statePath);
@@ -157,7 +141,7 @@ async function serve(command) {
157
141
  const deps = {
158
142
  statePath,
159
143
  readToken,
160
- clientForToken: (token) => createGitHubClient({ token, tokens: session ?? undefined }),
144
+ clientForToken: (token) => githubClient(token, process.env, session),
161
145
  readModels: async () => {
162
146
  const token = readToken();
163
147
  if (!token)
@@ -166,16 +150,12 @@ async function serve(command) {
166
150
  },
167
151
  launchWatcher: defaultLaunchWatcher,
168
152
  };
169
- if (!command.http) {
170
- const mcp = buildServer(command.selection, deps);
171
- await mcp.connect(new StdioServerTransport());
172
- return;
173
- }
174
- const http = await startHttpServer({ port: command.port, selection: command.selection, deps });
175
- console.error(`copilot-agents-mcp listening at ${http.url}`);
153
+ const mcp = buildServer(deps);
154
+ await mcp.connect(new StdioServerTransport());
176
155
  }
177
156
  async function watch() {
178
157
  warnIgnored(process.env);
158
+ warnGithubApiBase(process.env);
179
159
  const statePath = defaultStatePath();
180
160
  const pat = personalAccessToken(process.env);
181
161
  const session = pat ? null : await openAppSession(process.env, statePath);
@@ -190,12 +170,11 @@ async function watch() {
190
170
  if (!acquired)
191
171
  return;
192
172
  try {
193
- const interval = Number(process.env.COPILOT_AGENTS_POLL_INTERVAL_MS ?? "15000");
194
173
  await runWatcher({
195
- client: createGitHubClient({ token, tokens: session ?? undefined }),
174
+ client: githubClient(token, process.env, session),
196
175
  statePath,
197
- deliver: (notice) => deliverNotice(notice),
198
- intervalMs: Number.isFinite(interval) && interval >= 0 ? interval : 15_000,
176
+ deliver: (_notice, task) => deliverTaskNotice(task, statePath),
177
+ intervalMs: WATCH_POLL_INTERVAL_MS,
199
178
  });
200
179
  }
201
180
  finally {
@@ -213,7 +192,7 @@ async function main() {
213
192
  return;
214
193
  }
215
194
  try {
216
- const command = parseArgs(process.argv.slice(2), process.env);
195
+ const command = parseArgs(process.argv.slice(2));
217
196
  if (command.command === "watch")
218
197
  await watch();
219
198
  else if (command.command === "login")
@@ -224,14 +203,99 @@ async function main() {
224
203
  await status();
225
204
  else if (command.command === "version")
226
205
  console.log(packageVersion());
206
+ else if (command.command === "webhook")
207
+ await webhook(command);
227
208
  else
228
- await serve(command);
209
+ await serve();
229
210
  }
230
211
  catch (error) {
231
212
  console.error(error instanceof Error ? error.message : "Error.");
232
213
  process.exitCode = error instanceof Help ? 0 : 1;
233
214
  }
234
215
  }
216
+ async function webhook(command) {
217
+ try {
218
+ const statePath = defaultStatePath();
219
+ if (command.action === "list") {
220
+ for (const item of await listWebhooks(statePath)) {
221
+ console.log(`${item.owner}\t${item.host}\t${item.keyFilePath}\t${item.registeredAt}`);
222
+ }
223
+ }
224
+ else if (command.action === "remove") {
225
+ await removeWebhook(statePath, command.owner);
226
+ console.log("Webhook removed.");
227
+ }
228
+ else {
229
+ if ((!command.urlFile || !command.authFile) && (!process.stdin.isTTY || !process.stderr.isTTY)) {
230
+ throw new Error(WEBHOOK_INPUT_ERROR);
231
+ }
232
+ const url = command.urlFile ? await readWebhookInput(command.urlFile) : await hiddenPrompt("Webhook URL: ");
233
+ const authorization = command.authFile ? await readWebhookInput(command.authFile) : await hiddenPrompt("Authorization header value: ");
234
+ await registerWebhook(statePath, command.owner, url, authorization);
235
+ console.log("Webhook registered.");
236
+ }
237
+ }
238
+ catch (error) {
239
+ if (error instanceof WebhookValidationError)
240
+ throw error;
241
+ throw new Error(error instanceof Error && error.message === WEBHOOK_INPUT_ERROR ? WEBHOOK_INPUT_ERROR : WEBHOOK_ERROR);
242
+ }
243
+ }
244
+ async function readWebhookInput(path) {
245
+ try {
246
+ return (await readFile(path, "utf8")).trim();
247
+ }
248
+ catch {
249
+ throw new Error(WEBHOOK_INPUT_ERROR);
250
+ }
251
+ }
252
+ function hiddenPrompt(label) {
253
+ return new Promise((resolvePrompt, reject) => {
254
+ const input = process.stdin;
255
+ const wasRaw = input.isRaw;
256
+ let value = "";
257
+ const finish = (result) => {
258
+ input.off("data", onData);
259
+ input.off("end", onEnd);
260
+ input.off("error", onEnd);
261
+ try {
262
+ input.setRawMode(wasRaw);
263
+ }
264
+ catch {
265
+ result = undefined;
266
+ }
267
+ input.pause();
268
+ process.stderr.write("\n");
269
+ if (result === undefined)
270
+ reject(new Error(WEBHOOK_INPUT_ERROR));
271
+ else
272
+ resolvePrompt(result);
273
+ };
274
+ const onEnd = () => finish();
275
+ const onData = (data) => {
276
+ for (const char of data.toString("utf8")) {
277
+ if (char === "\r" || char === "\n") {
278
+ finish(value);
279
+ return;
280
+ }
281
+ if (char === "\u0003" || char === "\u0004" || char === "\u001b") {
282
+ finish();
283
+ return;
284
+ }
285
+ if (char === "\u007f" || char === "\b")
286
+ value = value.slice(0, -1);
287
+ else if (char >= " ")
288
+ value += char;
289
+ }
290
+ };
291
+ input.setRawMode(true);
292
+ input.on("data", onData);
293
+ input.once("end", onEnd);
294
+ input.once("error", onEnd);
295
+ process.stderr.write(label);
296
+ input.resume();
297
+ });
298
+ }
235
299
  function warnIgnored(env) {
236
300
  const message = ignoredTokenWarning(env);
237
301
  if (message)
@@ -303,14 +367,18 @@ async function status() {
303
367
  stored = session.stored();
304
368
  }
305
369
  const app = !pat && stored ? await readGitHubApp(stored.access_token, fetch) : null;
306
- console.log(statusReport({
370
+ const credential = statusReport({
307
371
  env: process.env,
308
372
  stored,
309
373
  keyring: opened.persistent ? "ready" : "memory",
310
374
  account: systemAccount(),
311
375
  appName: app?.name ?? null,
312
376
  appNotInstalled: app?.empty === true,
313
- }));
377
+ });
378
+ const local = await buildLocalStatusDiagnostics(process.env);
379
+ console.log(`${credential}\n\n${local.text}`);
380
+ if (local.failed)
381
+ process.exitCode = 1;
314
382
  }
315
383
  function invokedDirectly() {
316
384
  const entry = process.argv[1];
@@ -0,0 +1,23 @@
1
+ export function compactValue(value) {
2
+ if (value === undefined)
3
+ return undefined;
4
+ if (value === null)
5
+ return undefined;
6
+ if (Array.isArray(value)) {
7
+ const items = value.map((item) => compactValue(item)).filter((item) => item !== undefined);
8
+ return items;
9
+ }
10
+ if (typeof value === "object") {
11
+ const out = {};
12
+ for (const [key, raw] of Object.entries(value)) {
13
+ const next = compactValue(raw);
14
+ if (next !== undefined)
15
+ out[key] = next;
16
+ }
17
+ return out;
18
+ }
19
+ return value;
20
+ }
21
+ export function compactStringify(value) {
22
+ return JSON.stringify(compactValue(value));
23
+ }
@@ -0,0 +1,17 @@
1
+ import { mapRawState } from "./task-status.js";
2
+ export function deliveryForTask(task, activeChannels) {
3
+ if (task.notified_at || task.delivery_record?.status === "delivered")
4
+ return "delivered";
5
+ if (task.delivery_record?.status === "failed")
6
+ return "failed";
7
+ if (activeChannels.length === 0)
8
+ return "not_configured";
9
+ return "pending";
10
+ }
11
+ export function shouldSpawnWatcher(activeChannels) {
12
+ return activeChannels.length > 0;
13
+ }
14
+ export function webhookPayloadId(taskId, rawState) {
15
+ const mapped = mapRawState(rawState);
16
+ return `${taskId}:${mapped.status}`;
17
+ }