Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat: add GitHub issue and discussion tools for AI agents (#669)

Croff5137eedcfd46
diff --git a/README.md b/README.md
index 84d00133..188034b8 100644
--- a/README.md
+++ b/README.md
@@ -105,7 +105,7 @@ release.
- Or control the run queue through the API and do the work in your own implementation
- A run starts on an @mention in a comment, on an assignment, or on a schedule
- Tools for the services outside the tracker: Notion, Telegram, Threads, Instagram, Jina,
- Firecrawl, and Gitea
+ Firecrawl, Gitea, and GitHub
- Built-in chat with each agent, with its own conversation history
- Chat with an external agent too. The runner answers from your machine, streams the reply
and its tool calls, and resumes the same coding agent session on each message
diff --git a/apps/api/src/modules/agents/integrations/__tests__/integration/integrations.test.ts b/apps/api/src/modules/agents/integrations/__tests__/integration/integrations.test.ts
index 88b20b93..565dbe34 100644
--- a/apps/api/src/modules/agents/integrations/__tests__/integration/integrations.test.ts
+++ b/apps/api/src/modules/agents/integrations/__tests__/integration/integrations.test.ts
@@ -83,6 +83,20 @@ describe('integrations', () => {
});
});
+ it('stores a GitHub credential, showing the URL and masking the token', async () => {
+ const { asOwner, teamId } = await setup();
+ const res = await integrations(asOwner, teamId).post({
+ integrationKey: 'github',
+ credential: { baseUrl: 'https://github.example.com', token: 'github_pat_secret-abcd' },
+ });
+ expect(res.status).toBe(201);
+ expect(res.data!.redacted).toMatchObject({
+ baseUrl: 'https://github.example.com',
+ token: '••••abcd',
+ });
+ expect(JSON.stringify(res.data)).not.toContain('github_pat_secret');
+ });
+
it('rejects an unknown integration', async () => {
const { asOwner, teamId } = await setup();
const res = await integrations(asOwner, teamId).post({
@@ -159,6 +173,52 @@ describe('integrations', () => {
expect(upd.data!.redacted).toMatchObject({ botToken: '••••aaaa', defaultChatId: '99' });
});
+ // The tools send the stored token to baseUrl, so an edit that kept the token under a
+ // new address would hand it to whoever can edit but never read it.
+ it('refuses a new address that keeps the stored token', async () => {
+ const { asOwner, teamId } = await setup();
+ const created = await integrations(asOwner, teamId).post({
+ integrationKey: 'github',
+ credential: { token: 'github_pat_secret-abcd' },
+ });
+ const role = await createRole(asOwner, 'MKT', {
+ name: 'Integrator',
+ permissions: { integrations: { read: true, edit: true } },
+ });
+ const asMember = await addProjectMember(asOwner, 'MKT', role.data!.id);
+
+ const upd = await integrations(
+ asMember,
+ teamId,
+ )({ credentialId: created.data!.id }).patch({
+ credential: { baseUrl: 'https://collector.example' },
+ });
+ expect(upd.status).toBe(400);
+ const list = await integrations(asOwner, teamId).get();
+ expect(list.data!.items[0]!.redacted).not.toHaveProperty('baseUrl');
+ });
+
+ it('takes a new address with the token, and the same address without it', async () => {
+ const { asOwner, teamId } = await setup();
+ const created = await integrations(asOwner, teamId).post({
+ integrationKey: 'gitea',
+ credential: { baseUrl: 'https://git.example.com', token: 'token-secret-abcd' },
+ });
+ const credential = integrations(asOwner, teamId)({ credentialId: created.data!.id });
+
+ const same = await credential.patch({ credential: { baseUrl: 'https://git.example.com' } });
+ expect(same.status).toBe(200);
+
+ const moved = await credential.patch({
+ credential: { baseUrl: 'https://git2.example.com', token: 'token-secret-efgh' },
+ });
+ expect(moved.status).toBe(200);
+ expect(moved.data!.redacted).toMatchObject({
+ baseUrl: 'https://git2.example.com',
+ token: '••••efgh',
+ });
+ });
+
it('deletes a credential', async () => {
const { asOwner, teamId } = await setup();
const created = await integrations(asOwner, teamId).post({
diff --git a/apps/api/src/modules/agents/integrations/service.ts b/apps/api/src/modules/agents/integrations/service.ts
index c153d8cf..b0de88c3 100644
--- a/apps/api/src/modules/agents/integrations/service.ts
+++ b/apps/api/src/modules/agents/integrations/service.ts
@@ -159,6 +159,30 @@ export interface CredentialPatch {
credential?: Record<string, unknown>;
}
+// The tools send a credential's secrets to the address in its url fields. A new address
+// has to come with the secrets, or someone who may edit them but never read them could
+// send them to a host of their own.
+function assertSecretsResent(
+ fields: ConfigField[],
+ current: ToolConfig,
+ patch: Record<string, unknown>,
+): void {
+ const moved = fields.some(
+ (f) =>
+ f.type === 'url' &&
+ f.key in patch &&
+ String(patch[f.key] ?? '') !== String(current[f.key] ?? ''),
+ );
+ if (!moved) return;
+ const missing = fields.filter((f) => f.type === 'secret' && f.key in current && !patch[f.key]);
+ if (missing.length > 0) {
+ throw new HttpError(
+ 400,
+ `Enter ${missing.map((f) => f.label).join(', ')} again to change the address`,
+ );
+ }
+}
+
export async function updateCredential(
id: number,
teamId: number,
@@ -176,6 +200,7 @@ export async function updateCredential(
// Merge the submitted fields over the stored credential so unchanged secrets (left
// out by the form) are preserved, then re-validate the whole credential.
const current = (await decrypt(id, teamId)) ?? {};
+ assertSecretsResent(schema, current, patch.credential);
const merged = coerce(schema, { ...current, ...patch.credential });
const enc = encryptSecret(JSON.stringify(merged));
set.ciphertext = enc.ciphertext;
diff --git a/bun.lock b/bun.lock
index da00d79f..8e3d9cde 100644
--- a/bun.lock
+++ b/bun.lock
@@ -181,6 +181,7 @@
"name": "@repo/agent-tools",
"version": "0.0.0",
"dependencies": {
+ "@repo/net": "workspace:*",
"zod": "^4.6.7",
},
"devDependencies": {
diff --git a/packages/agent-tools/package.json b/packages/agent-tools/package.json
index 1ddbd5de..df3ae331 100644
--- a/packages/agent-tools/package.json
+++ b/packages/agent-tools/package.json
@@ -12,6 +12,7 @@
"test": "bun test"
},
"dependencies": {
+ "@repo/net": "workspace:*",
"zod": "^4.6.7"
},
"devDependencies": {
diff --git a/packages/agent-tools/src/registry.ts b/packages/agent-tools/src/registry.ts
index 692c7ea9..44a36536 100644
--- a/packages/agent-tools/src/registry.ts
+++ b/packages/agent-tools/src/registry.ts
@@ -13,6 +13,7 @@ import { threads } from './tools/threads';
import { instagram } from './tools/instagram';
import { notion } from './tools/notion';
import { gitea } from './tools/gitea';
+import { github } from './tools/github';
// The registry of tool integrations. Add an integration by creating its folder under
// tools/ and listing it here.
@@ -24,6 +25,7 @@ export const INTEGRATIONS: Integration[] = [
instagram,
notion,
gitea,
+ github,
];
const BY_KEY = new Map(INTEGRATIONS.map((i) => [i.key, i]));
diff --git a/packages/agent-tools/src/tools/gitea/__tests__/ssrf.test.ts b/packages/agent-tools/src/tools/gitea/__tests__/ssrf.test.ts
new file mode 100644
index 00000000..ba402b01
--- /dev/null
+++ b/packages/agent-tools/src/tools/gitea/__tests__/ssrf.test.ts
@@ -0,0 +1,23 @@
+import { afterAll, describe, expect, it } from 'bun:test';
+import { giteaRequest } from '../client';
+
+// The instance URL is entered by whoever edits the team's integrations, so a call to it
+// goes through the SSRF guard like every other configured address.
+describe('gitea client address', () => {
+ const hits: string[] = [];
+ const internal = Bun.serve({
+ hostname: '127.0.0.1',
+ port: 0,
+ fetch(req) {
+ hits.push(new URL(req.url).pathname);
+ return Response.json({ message: 'internal service answer' }, { status: 400 });
+ },
+ });
+ afterAll(() => internal.stop(true));
+
+ it('refuses a loopback instance URL without sending the request', async () => {
+ const credential = { baseUrl: `http://127.0.0.1:${internal.port}`, token: 't' };
+ await expect(giteaRequest(credential, 'GET', 'repos/a/b/issues')).rejects.toThrow();
+ expect(hits).toEqual([]);
+ });
+});
diff --git a/packages/agent-tools/src/tools/gitea/client.ts b/packages/agent-tools/src/tools/gitea/client.ts
index 7e17086f..f9923655 100644
--- a/packages/agent-tools/src/tools/gitea/client.ts
+++ b/packages/agent-tools/src/tools/gitea/client.ts
@@ -1,3 +1,4 @@
+import { pinnedFetch, UrlNotAllowedError } from '@repo/net';
import type { ToolConfig } from '../../types';
// Gitea REST API client, addressed at whatever instance the credential points at, so
@@ -62,7 +63,8 @@ export function issueRef(raw: unknown): number {
}
// Calls a Gitea endpoint and returns its parsed body. `path` is everything after
-// /api/v1/, query string included.
+// /api/v1/, query string included. The address is the credential's, so the call goes
+// through the SSRF guard; redirects are not followed.
export async function giteaRequest<T = Record<string, unknown>>(
credential: ToolConfig,
method: 'GET' | 'POST' | 'PATCH',
@@ -70,14 +72,25 @@ export async function giteaRequest<T = Record<string, unknown>>(
body?: Record<string, unknown>,
): Promise<T> {
const { baseUrl, token } = giteaCredential(credential);
- const res = await fetch(`${baseUrl}/api/v1/${path}`, {
- method,
- headers: {
- Authorization: `token ${token}`,
- ...(body ? { 'Content-Type': 'application/json' } : {}),
- },
- body: body ? JSON.stringify(body) : undefined,
- });
+ let res: Response;
+ try {
+ res = await pinnedFetch(`${baseUrl}/api/v1/${path}`, {
+ method,
+ headers: {
+ Authorization: `token ${token}`,
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ timeoutMs: 15_000,
+ });
+ } catch (err) {
+ if (err instanceof UrlNotAllowedError) {
+ throw new Error(
+ `The Gitea address is not allowed (${err.message}). An instance on a private network has to be named in SSRF_ALLOWED_HOSTS on the instance.`,
+ );
+ }
+ throw err;
+ }
const raw = await res.text();
let parsed: GiteaResponse = {};
try {
diff --git a/packages/agent-tools/src/tools/github/__tests__/client.test.ts b/packages/agent-tools/src/tools/github/__tests__/client.test.ts
new file mode 100644
index 00000000..d4f8b85d
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/__tests__/client.test.ts
@@ -0,0 +1,268 @@
+import { describe, it, expect, mock, beforeEach } from 'bun:test';
+import { UrlNotAllowedError } from '@repo/net';
+
+const pinnedFetch = mock(
+ async (_url: string, _init?: { headers?: Record<string, string>; body?: string }) =>
+ Response.json({}),
+);
+mock.module('@repo/net', () => ({ pinnedFetch, UrlNotAllowedError }));
+
+const { githubListIssues } = await import('../list-issues');
+const { githubCreateDiscussion } = await import('../create-discussion');
+const { githubGetDiscussion } = await import('../get-discussion');
+const { githubGraphql, githubRequest } = await import('../client');
+
+const credential = { token: 'github_pat_test' };
+
+function respond(status: number, body: unknown, headers: Record<string, string> = {}) {
+ pinnedFetch.mockImplementation(async () => Response.json(body, { status, headers }));
+}
+
+describe('github client', () => {
+ beforeEach(() => {
+ pinnedFetch.mockClear();
+ });
+
+ it('sends the headers GitHub requires', async () => {
+ respond(200, {});
+ await githubRequest(credential, 'GET', 'repos/acme/widgets/issues');
+ const [url, init] = pinnedFetch.mock.calls[0]!;
+ expect(url).toBe('https://api.github.com/repos/acme/widgets/issues');
+ expect(init?.headers).toMatchObject({
+ Accept: 'application/vnd.github+json',
+ Authorization: 'Bearer github_pat_test',
+ 'User-Agent': 'itsaplan',
+ 'X-GitHub-Api-Version': '2022-11-28',
+ });
+ });
+
+ it('calls an Enterprise Server instance under /api/v3', async () => {
+ respond(200, {});
+ await githubRequest(
+ { ...credential, baseUrl: 'https://github.example.com' },
+ 'GET',
+ 'repos/acme/widgets/issues',
+ );
+ expect(pinnedFetch.mock.calls[0]![0]).toBe(
+ 'https://github.example.com/api/v3/repos/acme/widgets/issues',
+ );
+ });
+
+ it('names SSRF_ALLOWED_HOSTS when the address is refused', async () => {
+ pinnedFetch.mockImplementation(async () => {
+ throw new UrlNotAllowedError('url must not point to a private or local address');
+ });
+ await expect(
+ githubRequest({ ...credential, baseUrl: 'https://ghe.internal' }, 'GET', 'x'),
+ ).rejects.toThrow('SSRF_ALLOWED_HOSTS');
+ });
+
+ it('drops pull requests from the issue list and reads either label shape', async () => {
+ respond(200, [
+ { number: 1, title: 'Bug', state: 'open', labels: [{ name: 'bug' }, 'p1'] },
+ { number: 2, title: 'Fix', state: 'open', pull_request: { url: 'x' } },
+ ]);
+ const result = (await githubListIssues.execute(credential, {
+ owner: 'acme',
+ repo: 'widgets',
+ })) as { issues: { number: number; labels: string[] }[] };
+ expect(result.issues.map((i) => i.number)).toEqual([1]);
+ expect(result.issues[0]!.labels).toEqual(['bug', 'p1']);
+ });
+
+ it('names a rate limit apart from a missing permission', async () => {
+ respond(403, { message: 'API rate limit exceeded' }, { 'x-ratelimit-remaining': '0' });
+ await expect(githubRequest(credential, 'GET', 'x')).rejects.toThrow(
+ 'GitHub rate limit reached',
+ );
+ });
+
+ it('names a secondary rate limit sent without retry-after', async () => {
+ respond(
+ 403,
+ { message: 'You have exceeded a secondary rate limit.' },
+ { 'x-ratelimit-remaining': '4999', 'x-ratelimit-reset': '1700000000' },
+ );
+ await expect(githubRequest(credential, 'POST', 'x', {})).rejects.toThrow(
+ 'Retry after at least a minute.',
+ );
+ });
+
+ it('names a 403 without a rate limit as a missing permission', async () => {
+ respond(403, { message: 'Resource not accessible' });
+ await expect(githubRequest(credential, 'GET', 'x')).rejects.toThrow('lacks permission');
+ });
+
+ it('names a renamed repository instead of following the redirect', async () => {
+ respond(301, { message: 'Moved Permanently' });
+ await expect(githubRequest(credential, 'GET', 'x')).rejects.toThrow('renamed or transferred');
+ respond(307, { message: 'Temporary Redirect' });
+ await expect(githubRequest(credential, 'PATCH', 'x', {})).rejects.toThrow(
+ 'renamed or transferred',
+ );
+ });
+
+ it('names a deleted issue on 410', async () => {
+ respond(410, { message: 'This issue was deleted' });
+ await expect(githubRequest(credential, 'PATCH', 'x', {})).rejects.toThrow(
+ 'The issue was deleted, or issues are disabled in this repository: This issue was deleted',
+ );
+ });
+
+ it('carries the validation causes of a 422', async () => {
+ respond(422, {
+ message: 'Validation Failed',
+ errors: [{ resource: 'Issue', field: 'title', code: 'missing_field' }],
+ });
+ await expect(githubRequest(credential, 'POST', 'x', {})).rejects.toThrow(
+ 'Validation Failed; title missing_field',
+ );
+ });
+
+ it('fails a GraphQL call that answers 200 with errors', async () => {
+ respond(200, {
+ data: { repository: null },
+ errors: [
+ {
+ type: 'NOT_FOUND',
+ message: "Could not resolve to a Repository with the name 'acme/nope'.",
+ },
+ ],
+ });
+ await expect(githubGraphql(credential, 'query { x }', {})).rejects.toThrow(
+ "GitHub rejected the request: Could not resolve to a Repository with the name 'acme/nope'.",
+ );
+ });
+
+ it('names a GraphQL rate limit', async () => {
+ respond(
+ 200,
+ { errors: [{ type: 'RATE_LIMITED', message: 'API rate limit exceeded' }] },
+ { 'x-ratelimit-remaining': '0' },
+ );
+ await expect(githubGraphql(credential, 'query { x }', {})).rejects.toThrow(
+ 'GitHub rate limit reached',
+ );
+ });
+
+ const repository = {
+ id: 'R_1',
+ hasDiscussionsEnabled: true,
+ discussionCategories: {
+ nodes: [
+ { id: 'C_general', name: 'General', slug: 'general' },
+ { id: 'C_qa', name: 'Q&A', slug: 'q-a' },
+ ],
+ },
+ };
+
+ it('starts a discussion in the category named by its slug', async () => {
+ pinnedFetch
+ .mockImplementationOnce(async () => Response.json({ data: { repository } }))
+ .mockImplementationOnce(async () =>
+ Response.json({
+ data: {
+ createDiscussion: {
+ discussion: { number: 5, title: 'How?', url: 'u', category: { name: 'Q&A' } },
+ },
+ },
+ }),
+ );
+ const result = await githubCreateDiscussion.execute(
+ { ...credential, baseUrl: 'https://github.example.com' },
+ { owner: 'acme', repo: 'widgets', category: 'Q-A', title: 'How?', body: 'Text' },
+ );
+ expect(result).toEqual({ number: 5, title: 'How?', category: 'Q&A', url: 'u' });
+ const [url, init] = pinnedFetch.mock.calls[1]!;
+ expect(url).toBe('https://github.example.com/api/graphql');
+ expect(JSON.parse(String(init?.body)).variables).toEqual({
+ input: { repositoryId: 'R_1', categoryId: 'C_qa', title: 'How?', body: 'Text' },
+ });
+ });
+
+ it('answers an unknown category with the categories the repository has', async () => {
+ respond(200, { data: { repository } });
+ await expect(
+ githubCreateDiscussion.execute(credential, {
+ owner: 'acme',
+ repo: 'widgets',
+ category: 'Ideas',
+ title: 't',
+ body: 'b',
+ }),
+ ).rejects.toThrow('The repository has: General, Q&A.');
+ expect(pinnedFetch.mock.calls).toHaveLength(1);
+ });
+
+ it('reads a discussion with its comments, replies and the next page', async () => {
+ const author = { login: 'octo' };
+ respond(200, {
+ data: {
+ repository: {
+ discussion: {
+ number: 7,
+ title: 'How?',
+ body: 'Question',
+ url: 'u',
+ createdAt: 't0',
+ closed: false,
+ isAnswered: true,
+ author: null,
+ category: { name: 'Q&A' },
+ comments: {
+ totalCount: 30,
+ nodes: [
+ {
+ id: 'DC_1',
+ url: 'u1',
+ body: 'Answer',
+ createdAt: 't1',
+ isAnswer: true,
+ author,
+ replies: {
+ totalCount: 21,
+ nodes: [{ id: 'DC_2', url: 'u2', body: 'Thanks', createdAt: 't2', author }],
+ },
+ },
+ ],
+ pageInfo: { hasNextPage: true, endCursor: 'c1' },
+ },
+ },
+ },
+ },
+ });
+ const result = await githubGetDiscussion.execute(credential, {
+ owner: 'acme',
+ repo: 'widgets',
+ discussion: 'https://github.com/acme/widgets/discussions/7#discussioncomment-1',
+ });
+ expect(JSON.parse(String(pinnedFetch.mock.calls[0]![1]?.body)).variables).toMatchObject({
+ number: 7,
+ first: 20,
+ after: null,
+ });
+ expect(result).toMatchObject({
+ number: 7,
+ author: null,
+ answered: true,
+ commentCount: 30,
+ nextCursor: 'c1',
+ comments: [
+ {
+ id: 'DC_1',
+ author: 'octo',
+ isAnswer: true,
+ replies: [{ id: 'DC_2', author: 'octo', body: 'Thanks' }],
+ moreReplies: 20,
+ },
+ ],
+ });
+ });
+
+ it('names a discussion that does not exist', async () => {
+ respond(200, { data: { repository: { discussion: null } } });
+ await expect(
+ githubGetDiscussion.execute(credential, { owner: 'acme', repo: 'widgets', discussion: 99 }),
+ ).rejects.toThrow('Discussion #99 not found in acme/widgets.');
+ });
+});
diff --git a/packages/agent-tools/src/tools/github/__tests__/ref.test.ts b/packages/agent-tools/src/tools/github/__tests__/ref.test.ts
new file mode 100644
index 00000000..7864c63b
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/__tests__/ref.test.ts
@@ -0,0 +1,57 @@
+import { describe, it, expect } from 'bun:test';
+import { apiRoot, graphqlUrl, numberRef, repoPath } from '../client';
+
+describe('github helpers', () => {
+ it('takes a number bare, hashed, or from the URL of its kind', () => {
+ expect(numberRef(12, 'issue')).toBe(12);
+ expect(numberRef('#12', 'issue')).toBe(12);
+ expect(numberRef('https://github.com/acme/widgets/issues/12', 'issue')).toBe(12);
+ expect(numberRef('https://github.com/acme/widgets/issues/12#issuecomment-345', 'issue')).toBe(
+ 12,
+ );
+ expect(
+ numberRef(
+ 'https://github.com/acme/widgets/discussions/7#discussioncomment-345',
+ 'discussion',
+ ),
+ ).toBe(7);
+ expect(() => numberRef('https://github.com/acme/widgets/discussions/7', 'issue')).toThrow(
+ 'not a GitHub issue number or URL',
+ );
+ expect(() => numberRef('a discussion', 'discussion')).toThrow(
+ 'not a GitHub discussion number or URL',
+ );
+ });
+
+ it('builds the repository path with each segment encoded', () => {
+ expect(repoPath('acme', 'widgets')).toBe('repos/acme/widgets');
+ expect(repoPath('a cme', 'wi/dgets')).toBe('repos/a%20cme/wi%2Fdgets');
+ });
+
+ it('finds the API root of github.com, GHE.com and an Enterprise Server', () => {
+ expect(apiRoot({})).toBe('https://api.github.com');
+ expect(apiRoot({ baseUrl: 'https://github.com' })).toBe('https://api.github.com');
+ expect(apiRoot({ baseUrl: 'https://api.github.com/' })).toBe('https://api.github.com');
+ expect(apiRoot({ baseUrl: 'https://octocorp.ghe.com' })).toBe('https://api.octocorp.ghe.com');
+ expect(apiRoot({ baseUrl: 'https://api.octocorp.ghe.com' })).toBe(
+ 'https://api.octocorp.ghe.com',
+ );
+ expect(apiRoot({ baseUrl: 'https://github.example.com/' })).toBe(
+ 'https://github.example.com/api/v3',
+ );
+ expect(apiRoot({ baseUrl: 'https://github.example.com/api/v3' })).toBe(
+ 'https://github.example.com/api/v3',
+ );
+ expect(() => apiRoot({ baseUrl: 'github' })).toThrow('not a valid GitHub address');
+ });
+
+ it('finds the GraphQL endpoint beside the API root', () => {
+ expect(graphqlUrl({})).toBe('https://api.github.com/graphql');
+ expect(graphqlUrl({ baseUrl: 'https://octocorp.ghe.com' })).toBe(
+ 'https://api.octocorp.ghe.com/graphql',
+ );
+ expect(graphqlUrl({ baseUrl: 'https://github.example.com' })).toBe(
+ 'https://github.example.com/api/graphql',
+ );
+ });
+});
diff --git a/packages/agent-tools/src/tools/github/client.ts b/packages/agent-tools/src/tools/github/client.ts
new file mode 100644
index 00000000..6286de69
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/client.ts
@@ -0,0 +1,248 @@
+import { pinnedFetch, UrlNotAllowedError } from '@repo/net';
+import { z } from 'zod';
+import type { ToolConfig } from '../../types';
+
+// GitHub API client for github.com, GitHub Enterprise Cloud with data residency
+// (GHE.com) and GitHub Enterprise Server. Issues go through the REST API, discussions
+// through GraphQL, which is the only API GitHub offers for them. Failures are turned
+// into messages a person can act on, because a tool error goes straight to the model.
+
+// The newer 2026-03-10 is unknown to GitHub Enterprise Server before 3.22, which
+// answers it with 410.
+const API_VERSION = '2022-11-28';
+
+export interface GithubIssue {
+ number?: number;
+ title?: string;
+ state?: string;
+ html_url?: string;
+ updated_at?: string;
+ labels?: (string | { name?: string })[];
+ pull_request?: unknown;
+ [key: string]: unknown;
+}
+
+interface GithubResponse {
+ message?: string;
+ errors?: { field?: string; code?: string; message?: string; type?: string }[];
+ data?: unknown;
+ [key: string]: unknown;
+}
+
+// The REST API root for the credential's host. github.com serves it from
+// api.github.com, a GHE.com subdomain from api.SUBDOMAIN.ghe.com, and an Enterprise
+// Server instance from /api/v3 on its own host.
+export function apiRoot(credential: ToolConfig): string {
+ const raw = String(credential.baseUrl ?? '').trim();
+ if (!raw) return 'https://api.github.com';
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ throw new Error(`"${raw}" is not a valid GitHub address.`);
+ }
+ const host = url.hostname.toLowerCase();
+ if (host === 'github.com' || host === 'api.github.com') return 'https://api.github.com';
+ if (host.endsWith('.ghe.com')) return `https://api.${host.replace(/^api\./, '')}`;
+ return `${url.origin}/api/v3`;
+}
+
+// The GraphQL endpoint sits beside the REST root, except on an Enterprise Server,
+// where it is /api/graphql rather than /api/v3/graphql.
+export function graphqlUrl(credential: ToolConfig): string {
+ return `${apiRoot(credential).replace(/\/v3$/, '')}/graphql`;
+}
+
+// The owner/repo part of an endpoint path, encoded so a stray slash cannot redirect
+// the call to another repository.
+export function repoPath(owner: unknown, repo: unknown): string {
+ return `repos/${encodeURIComponent(String(owner))}/${encodeURIComponent(String(repo))}`;
+}
+
+export const repoInput = {
+ owner: z.string().min(1).describe('Repository owner (user or organization).'),
+ repo: z.string().min(1).describe('Repository name.'),
+};
+
+export const issueInput = z
+ .union([z.number(), z.string()])
+ .describe('Issue number, #number, or the issue URL.');
+
+export const discussionInput = z
+ .union([z.number(), z.string()])
+ .describe('Discussion number, #number, or the discussion URL.');
+
+const REF_PATHS = { issue: 'issues|pull', discussion: 'discussions' };
+
+// The bare number of an issue or a discussion. A model passes the number bare, with a
+// # prefix, or as the URL it was given, which can carry a comment anchor with digits of
+// its own; all three are accepted.
+export function numberRef(raw: unknown, kind: keyof typeof REF_PATHS): number {
+ const value = String(raw ?? '').trim();
+ const match =
+ value.match(/^#?(\d+)$/) ?? value.match(new RegExp(`/(?:${REF_PATHS[kind]})/(\\d+)`));
+ if (!match) throw new Error(`"${value}" is not a GitHub ${kind} number or URL.`);
+ return Number(match[1]);
+}
+
+// What GitHub said went wrong: the message of a REST error with the causes of a 422,
+// or the messages of a GraphQL errors array.
+function causes(body: GithubResponse): string {
+ const errors = (body.errors ?? []).map(
+ (e) => e.message ?? [e.field, e.code].filter(Boolean).join(' '),
+ );
+ return [body.message, ...errors].filter(Boolean).join('; ');
+}
+
+// A primary rate limit answers 403 or 429 over REST and 200 with an error over
+// GraphQL, with x-ratelimit-remaining at 0 either way. A secondary limit answers 403
+// or 429 with retry-after or only its message; without retry-after GitHub asks to
+// wait at least a minute, since x-ratelimit-reset belongs to the primary limit.
+function rateLimit(res: Response, body: GithubResponse): string | null {
+ const exhausted = res.headers.get('x-ratelimit-remaining') === '0';
+ const limited =
+ res.status === 429 ||
+ (res.status === 403 &&
+ (exhausted || res.headers.has('retry-after') || /rate limit/i.test(body.message ?? ''))) ||
+ (res.ok && (exhausted || (body.errors ?? []).some((e) => e.type === 'RATE_LIMITED')));
+ if (!limited) return null;
+ const detail = causes(body);
+ const retryAfter = res.headers.get('retry-after');
+ const reset = Number(res.headers.get('x-ratelimit-reset'));
+ let when = 'Retry after at least a minute.';
+ if (retryAfter) when = `Retry after ${retryAfter} seconds.`;
+ else if (exhausted && reset) when = `Retry after ${new Date(reset * 1000).toISOString()}.`;
+ return `GitHub rate limit reached${detail ? `: ${detail}` : ''}. ${when}`;
+}
+
+function explain(res: Response, body: GithubResponse): string {
+ const limited = rateLimit(res, body);
+ if (limited) return limited;
+ const message = causes(body);
+ const detail = message ? `: ${message}` : '';
+ switch (res.status) {
+ // A renamed repository answers 301 or 307 depending on the method; 301 on an
+ // issue also means it was moved to another repository.
+ case 301:
+ case 307:
+ return 'The repository was renamed or transferred, or the issue was moved to another repository. Use the current owner, name and number.';
+ case 401:
+ return `The GitHub token is invalid, expired, or was revoked${detail}`;
+ case 403:
+ return `The GitHub token lacks permission for this action${detail}`;
+ case 404:
+ return 'Repository or issue not found. Check the owner/repo spelling and that the token can access the repository: GitHub answers 404 for a private repository the token cannot see.';
+ case 410:
+ return `The issue was deleted, or issues are disabled in this repository${detail}`;
+ case 422:
+ return `GitHub rejected the request as invalid${detail}`;
+ default:
+ return `GitHub API error (${res.status})${detail}`;
+ }
+}
+
+// Sends one call to the credential's host. The address is the credential's, so the
+// call goes through the SSRF guard; redirects are not followed.
+async function send(
+ credential: ToolConfig,
+ method: 'GET' | 'POST' | 'PATCH',
+ url: string,
+ headers: Record<string, string>,
+ body?: Record<string, unknown>,
+): Promise<{ res: Response; parsed: GithubResponse }> {
+ const token = credential.token ? String(credential.token) : '';
+ if (!token) throw new Error('No GitHub token configured.');
+ let res: Response;
+ try {
+ res = await pinnedFetch(url, {
+ method,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'User-Agent': 'itsaplan',
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
+ ...headers,
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ timeoutMs: 15_000,
+ });
+ } catch (err) {
+ if (err instanceof UrlNotAllowedError) {
+ throw new Error(
+ `The GitHub address is not allowed (${err.message}). A GitHub Enterprise Server on a private network has to be named in SSRF_ALLOWED_HOSTS on the instance.`,
+ );
+ }
+ throw err;
+ }
+ const raw = await res.text();
+ let parsed: GithubResponse = {};
+ try {
+ parsed = raw ? (JSON.parse(raw) as GithubResponse) : {};
+ } catch {
+ /* non-JSON error page */
+ }
+ return { res, parsed };
+}
+
+// Calls a REST endpoint and returns its parsed body. `path` is everything after the
+// API root, query string included.
+export async function githubRequest<T = Record<string, unknown>>(
+ credential: ToolConfig,
+ method: 'GET' | 'POST' | 'PATCH',
+ path: string,
+ body?: Record<string, unknown>,
+): Promise<T> {
+ const { res, parsed } = await send(
+ credential,
+ method,
+ `${apiRoot(credential)}/${path}`,
+ { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': API_VERSION },
+ body,
+ );
+ if (!res.ok) throw new Error(explain(res, parsed));
+ return parsed as T;
+}
+
+// Runs a GraphQL query or mutation and returns its data. GraphQL answers a failed
+// call, a missing repository included, with 200 and an errors array.
+export async function githubGraphql<T>(
+ credential: ToolConfig,
+ query: string,
+ variables: Record<string, unknown>,
+): Promise<T> {
+ const { res, parsed } = await send(
+ credential,
+ 'POST',
+ graphqlUrl(credential),
+ {},
+ {
+ query,
+ variables,
+ },
+ );
+ if (!res.ok) throw new Error(explain(res, parsed));
+ if (parsed.errors?.length) {
+ throw new Error(rateLimit(res, parsed) ?? `GitHub rejected the request: ${causes(parsed)}`);
+ }
+ return parsed.data as T;
+}
+
+// The node id of a discussion, which every discussion mutation takes, from the number
+// a person knows it by.
+export async function discussionId(
+ credential: ToolConfig,
+ owner: unknown,
+ repo: unknown,
+ ref: unknown,
+): Promise<string> {
+ const number = numberRef(ref, 'discussion');
+ const data = await githubGraphql<{ repository: { discussion: { id: string } | null } | null }>(
+ credential,
+ `query($owner: String!, $repo: String!, $number: Int!) {
+ repository(owner: $owner, name: $repo) { discussion(number: $number) { id } }
+ }`,
+ { owner: String(owner), repo: String(repo), number },
+ );
+ const id = data.repository?.discussion?.id;
+ if (!id) throw new Error(`Discussion #${number} not found in ${owner}/${repo}.`);
+ return id;
+}
diff --git a/packages/agent-tools/src/tools/github/comment-discussion.ts b/packages/agent-tools/src/tools/github/comment-discussion.ts
new file mode 100644
index 00000000..69b09749
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/comment-discussion.ts
@@ -0,0 +1,29 @@
+import { z } from 'zod';
+import type { CustomToolEntry } from '../../types';
+import { discussionId, discussionInput, githubGraphql, repoInput } from './client';
+
+export const githubCommentDiscussion: CustomToolEntry = {
+ key: 'github_comment_discussion',
+ label: 'GitHub Comment Discussion',
+ description:
+ 'Comment on a discussion in a GitHub repository. The text is markdown. Returns the id and the URL of the new comment.',
+ inputSchema: z.object({
+ ...repoInput,
+ discussion: discussionInput,
+ body: z.string().min(1).describe('The comment text, as markdown.'),
+ }),
+ execute: async (credential, input) => {
+ const id = await discussionId(credential, input.owner, input.repo, input.discussion);
+ const data = await githubGraphql<{
+ addDiscussionComment: { comment: { id: string; url: string } };
+ }>(
+ credential,
+ `mutation($input: AddDiscussionCommentInput!) {
+ addDiscussionComment(input: $input) { comment { id url } }
+ }`,
+ { input: { discussionId: id, body: String(input.body) } },
+ );
+ const comment = data.addDiscussionComment.comment;
+ return { id: comment.id, url: comment.url };
+ },
+};
diff --git a/packages/agent-tools/src/tools/github/comment-issue.ts b/packages/agent-tools/src/tools/github/comment-issue.ts
new file mode 100644
index 00000000..0de2d56f
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/comment-issue.ts
@@ -0,0 +1,24 @@
+import { z } from 'zod';
+import type { CustomToolEntry } from '../../types';
+import { githubRequest, issueInput, numberRef, repoInput, repoPath } from './client';
+
+export const githubCommentIssue: CustomToolEntry = {
+ key: 'github_comment_issue',
+ label: 'GitHub Comment Issue',
+ description:
+ 'Comment on an issue in a GitHub repository. The text is markdown. Returns the id of the new comment.',
+ inputSchema: z.object({
+ ...repoInput,
+ issue: issueInput,
+ body: z.string().min(1).describe('The comment text, as markdown.'),
+ }),
+ execute: async (credential, input) => {
+ const comment = await githubRequest<{ id?: number; html_url?: string }>(
+ credential,
+ 'POST',
+ `${repoPath(input.owner, input.repo)}/issues/${numberRef(input.issue, 'issue')}/comments`,
+ { body: String(input.body) },
+ );
+ return { id: comment.id ?? null, url: comment.html_url ?? null };
+ },
+};
diff --git a/packages/agent-tools/src/tools/github/create-discussion.ts b/packages/agent-tools/src/tools/github/create-discussion.ts
new file mode 100644
index 00000000..1fa2df9e
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/create-discussion.ts
@@ -0,0 +1,85 @@
+import { z } from 'zod';
+import type { CustomToolEntry } from '../../types';
+import { githubGraphql, repoInput } from './client';
+
+interface Category {
+ id: string;
+ name: string;
+ slug: string;
+}
+
+// GitHub takes the repository and the category as node ids, so both are looked up
+// first; a repository has at most 25 categories, all read at once.
+export const githubCreateDiscussion: CustomToolEntry = {
+ key: 'github_create_discussion',
+ label: 'GitHub Create Discussion',
+ description:
+ 'Start a discussion in a GitHub repository, in one of its discussion categories. The body is markdown. An unknown category is answered with the list of the categories the repository has. Returns the new discussion with its number, which the other GitHub discussion tools take.',
+ inputSchema: z.object({
+ ...repoInput,
+ category: z.string().min(1).describe('Category name or slug, e.g. General or q-a.'),
+ title: z.string().min(1).describe('Discussion title.'),
+ body: z.string().min(1).describe('Discussion text, as markdown.'),
+ }),
+ execute: async (credential, input) => {
+ const data = await githubGraphql<{
+ repository: {
+ id: string;
+ hasDiscussionsEnabled: boolean;
+ discussionCategories: { nodes: Category[] };
+ } | null;
+ }>(
+ credential,
+ `query($owner: String!, $repo: String!) {
+ repository(owner: $owner, name: $repo) {
+ id
+ hasDiscussionsEnabled
+ discussionCategories(first: 25) { nodes { id name slug } }
+ }
+ }`,
+ { owner: String(input.owner), repo: String(input.repo) },
+ );
+ const repository = data.repository;
+ if (!repository) throw new Error(`Repository ${input.owner}/${input.repo} not found.`);
+ if (!repository.hasDiscussionsEnabled) {
+ throw new Error('Discussions are disabled in this repository.');
+ }
+ const wanted = String(input.category).trim().toLowerCase();
+ const categories = repository.discussionCategories.nodes;
+ const category = categories.find(
+ (c) => c.name.toLowerCase() === wanted || c.slug.toLowerCase() === wanted,
+ );
+ if (!category) {
+ throw new Error(
+ `No discussion category "${input.category}". The repository has: ${categories.map((c) => c.name).join(', ')}.`,
+ );
+ }
+ const created = await githubGraphql<{
+ createDiscussion: {
+ discussion: { number: number; title: string; url: string; category: { name: string } };
+ };
+ }>(
+ credential,
+ `mutation($input: CreateDiscussionInput!) {
+ createDiscussion(input: $input) {
+ discussion { number title url category { name } }
+ }
+ }`,
+ {
+ input: {
+ repositoryId: repository.id,
+ categoryId: category.id,
+ title: String(input.title),
+ body: String(input.body),
+ },
+ },
+ );
+ const discussion = created.createDiscussion.discussion;
+ return {
+ number: discussion.number,
+ title: discussion.title,
+ category: discussion.category.name,
+ url: discussion.url,
+ };
+ },
+};
diff --git a/packages/agent-tools/src/tools/github/create-issue.ts b/packages/agent-tools/src/tools/github/create-issue.ts
new file mode 100644
index 00000000..6dee3d13
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/create-issue.ts
@@ -0,0 +1,32 @@
+import { z } from 'zod';
+import type { CustomToolEntry } from '../../types';
+import { githubRequest, repoInput, repoPath, type GithubIssue } from './client';
+
+export const githubCreateIssue: CustomToolEntry = {
+ key: 'github_create_issue',
+ label: 'GitHub Create Issue',
+ description:
+ 'Create an issue in a GitHub repository. The body is markdown. Returns the new issue with its number, which the other GitHub tools take.',
+ inputSchema: z.object({
+ ...repoInput,
+ title: z.string().min(1).describe('Issue title.'),
+ body: z.string().optional().describe('Issue description, as markdown.'),
+ }),
+ execute: async (credential, input) => {
+ const issue = await githubRequest<GithubIssue>(
+ credential,
+ 'POST',
+ `${repoPath(input.owner, input.repo)}/issues`,
+ {
+ title: String(input.title),
+ ...(input.body !== undefined ? { body: String(input.body) } : {}),
+ },
+ );
+ return {
+ number: issue.number,
+ title: issue.title ?? null,
+ state: issue.state ?? null,
+ url: issue.html_url ?? null,
+ };
+ },
+};
diff --git a/packages/agent-tools/src/tools/github/get-discussion.ts b/packages/agent-tools/src/tools/github/get-discussion.ts
new file mode 100644
index 00000000..89c78171
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/get-discussion.ts
@@ -0,0 +1,124 @@
+import { z } from 'zod';
+import type { CustomToolEntry } from '../../types';
+import { discussionInput, githubGraphql, numberRef, repoInput } from './client';
+
+const REPLIES = 20;
+
+interface Reply {
+ id: string;
+ url: string;
+ body: string;
+ createdAt: string;
+ author: { login: string } | null;
+}
+
+interface Comment extends Reply {
+ isAnswer: boolean;
+ replies: { totalCount: number; nodes: Reply[] };
+}
+
+interface Discussion {
+ number: number;
+ title: string;
+ body: string;
+ url: string;
+ createdAt: string;
+ closed: boolean;
+ isAnswered: boolean | null;
+ author: { login: string } | null;
+ category: { name: string };
+ comments: {
+ totalCount: number;
+ nodes: Comment[];
+ pageInfo: { hasNextPage: boolean; endCursor: string | null };
+ };
+}
+
+function reply(r: Reply) {
+ return {
+ id: r.id,
+ author: r.author?.login ?? null,
+ body: r.body,
+ createdAt: r.createdAt,
+ url: r.url,
+ };
+}
+
+// ponytail: up to REPLIES replies per comment, the rest only counted (moreReplies);
+// page DiscussionComment.replies if long threads turn up.
+export const githubGetDiscussion: CustomToolEntry = {
+ key: 'github_get_discussion',
+ label: 'GitHub Get Discussion',
+ description:
+ 'Read a discussion in a GitHub repository: its markdown body, category and state, and its comments with the replies under each. Returns nextCursor when there are more comments; pass it as cursor to get the next page.',
+ inputSchema: z.object({
+ ...repoInput,
+ discussion: discussionInput,
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(50)
+ .optional()
+ .describe('How many comments to return, 1-50 (default 20).'),
+ cursor: z.string().optional().describe('nextCursor from the previous page of comments.'),
+ }),
+ execute: async (credential, input) => {
+ const number = numberRef(input.discussion, 'discussion');
+ const data = await githubGraphql<{ repository: { discussion: Discussion | null } | null }>(
+ credential,
+ `query($owner: String!, $repo: String!, $number: Int!, $first: Int!, $after: String, $replies: Int!) {
+ repository(owner: $owner, name: $repo) {
+ discussion(number: $number) {
+ number title body url createdAt closed isAnswered
+ author { login }
+ category { name }
+ comments(first: $first, after: $after) {
+ totalCount
+ nodes {
+ id url body createdAt isAnswer
+ author { login }
+ replies(first: $replies) {
+ totalCount
+ nodes { id url body createdAt author { login } }
+ }
+ }
+ pageInfo { hasNextPage endCursor }
+ }
+ }
+ }
+ }`,
+ {
+ owner: String(input.owner),
+ repo: String(input.repo),
+ number,
+ first: input.limit ?? 20,
+ after: input.cursor ?? null,
+ replies: REPLIES,
+ },
+ );
+ const d = data.repository?.discussion;
+ if (!d) throw new Error(`Discussion #${number} not found in ${input.owner}/${input.repo}.`);
+ return {
+ number: d.number,
+ title: d.title,
+ body: d.body,
+ author: d.author?.login ?? null,
+ category: d.category.name,
+ closed: d.closed,
+ answered: d.isAnswered ?? false,
+ url: d.url,
+ createdAt: d.createdAt,
+ commentCount: d.comments.totalCount,
+ comments: d.comments.nodes.map((c) => ({
+ ...reply(c),
+ isAnswer: c.isAnswer,
+ replies: c.replies.nodes.map(reply),
+ ...(c.replies.totalCount > c.replies.nodes.length
+ ? { moreReplies: c.replies.totalCount - c.replies.nodes.length }
+ : {}),
+ })),
+ nextCursor: d.comments.pageInfo.hasNextPage ? d.comments.pageInfo.endCursor : null,
+ };
+ },
+};
diff --git a/packages/agent-tools/src/tools/github/index.ts b/packages/agent-tools/src/tools/github/index.ts
new file mode 100644
index 00000000..66970efe
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/index.ts
@@ -0,0 +1,46 @@
+import type { Integration } from '../../types';
+import { githubListIssues } from './list-issues';
+import { githubCreateIssue } from './create-issue';
+import { githubUpdateIssue } from './update-issue';
+import { githubCommentIssue } from './comment-issue';
+import { githubListDiscussions } from './list-discussions';
+import { githubGetDiscussion } from './get-discussion';
+import { githubCreateDiscussion } from './create-discussion';
+import { githubUpdateDiscussion } from './update-discussion';
+import { githubCommentDiscussion } from './comment-discussion';
+
+// GitHub: the issues and discussions of a repository an agent can read and act on.
+// One credential is one personal access token on github.com, on GHE.com, or on a
+// GitHub Enterprise Server instance.
+export const github: Integration = {
+ key: 'github',
+ label: 'GitHub',
+ credentialSchema: [
+ {
+ key: 'baseUrl',
+ label: 'Instance URL',
+ type: 'url',
+ required: false,
+ placeholder: 'https://github.com',
+ help: 'Leave empty for github.com. For GitHub Enterprise Server, the address of your instance; for GitHub Enterprise Cloud with data residency, your SUBDOMAIN.ghe.com address.',
+ },
+ {
+ key: 'token',
+ label: 'Access token',
+ type: 'secret',
+ required: true,
+ help: 'Fine-grained personal access token with the Issues and Discussions repository permissions set to Read and write, for the repositories the agent works in (Settings, Developer settings). A classic token needs the repo scope.',
+ },
+ ],
+ tools: [
+ githubListIssues,
+ githubCreateIssue,
+ githubUpdateIssue,
+ githubCommentIssue,
+ githubListDiscussions,
+ githubGetDiscussion,
+ githubCreateDiscussion,
+ githubUpdateDiscussion,
+ githubCommentDiscussion,
+ ],
+};
diff --git a/packages/agent-tools/src/tools/github/list-discussions.ts b/packages/agent-tools/src/tools/github/list-discussions.ts
new file mode 100644
index 00000000..00e1bdf9
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/list-discussions.ts
@@ -0,0 +1,81 @@
+import { z } from 'zod';
+import type { CustomToolEntry } from '../../types';
+import { githubGraphql, repoInput } from './client';
+
+interface DiscussionNode {
+ number: number;
+ title: string;
+ url: string;
+ closed: boolean;
+ isAnswered: boolean | null;
+ updatedAt: string;
+ category: { name: string };
+ comments: { totalCount: number };
+}
+
+const STATES = { open: ['OPEN'], closed: ['CLOSED'], all: [] };
+
+export const githubListDiscussions: CustomToolEntry = {
+ key: 'github_list_discussions',
+ label: 'GitHub List Discussions',
+ description:
+ 'List discussions in a GitHub repository, most recently updated first. Returns each discussion with its number, which the other GitHub discussion tools take, and nextCursor when there are more; pass it as cursor to get the next page.',
+ inputSchema: z.object({
+ ...repoInput,
+ state: z.enum(['open', 'closed', 'all']).optional().describe('Filter by state (default open).'),
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(50)
+ .optional()
+ .describe('How many discussions to return, 1-50 (default 10).'),
+ cursor: z.string().optional().describe('nextCursor from the previous page.'),
+ }),
+ execute: async (credential, input) => {
+ const data = await githubGraphql<{
+ repository: {
+ discussions: {
+ nodes: DiscussionNode[];
+ pageInfo: { hasNextPage: boolean; endCursor: string | null };
+ };
+ } | null;
+ }>(
+ credential,
+ `query($owner: String!, $repo: String!, $first: Int!, $after: String, $states: [DiscussionState!]) {
+ repository(owner: $owner, name: $repo) {
+ discussions(first: $first, after: $after, states: $states, orderBy: { field: UPDATED_AT, direction: DESC }) {
+ nodes {
+ number title url closed isAnswered updatedAt
+ category { name }
+ comments { totalCount }
+ }
+ pageInfo { hasNextPage endCursor }
+ }
+ }
+ }`,
+ {
+ owner: String(input.owner),
+ repo: String(input.repo),
+ first: input.limit ?? 10,
+ after: input.cursor ?? null,
+ states: STATES[(input.state as keyof typeof STATES | undefined) ?? 'open'],
+ },
+ );
+ if (!data.repository) throw new Error(`Repository ${input.owner}/${input.repo} not found.`);
+ const { nodes, pageInfo } = data.repository.discussions;
+ return {
+ discussions: nodes.map((d) => ({
+ number: d.number,
+ title: d.title,
+ category: d.category.name,
+ closed: d.closed,
+ answered: d.isAnswered ?? false,
+ comments: d.comments.totalCount,
+ url: d.url,
+ updatedAt: d.updatedAt,
+ })),
+ nextCursor: pageInfo.hasNextPage ? pageInfo.endCursor : null,
+ };
+ },
+};
diff --git a/packages/agent-tools/src/tools/github/list-issues.ts b/packages/agent-tools/src/tools/github/list-issues.ts
new file mode 100644
index 00000000..3a9aa6d1
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/list-issues.ts
@@ -0,0 +1,50 @@
+import { z } from 'zod';
+import type { CustomToolEntry } from '../../types';
+import { githubRequest, repoInput, repoPath, type GithubIssue } from './client';
+
+// GitHub returns pull requests from this endpoint too and has no filter for them, so a
+// page can hold fewer issues than the limit.
+export const githubListIssues: CustomToolEntry = {
+ key: 'github_list_issues',
+ label: 'GitHub List Issues',
+ description:
+ 'List issues in a GitHub repository, most recently created first. Returns each issue with its number, which the other GitHub tools take. Pull requests are not included, so a page can hold fewer issues than the limit; ask for the next page to see more.',
+ inputSchema: z.object({
+ ...repoInput,
+ state: z.enum(['open', 'closed', 'all']).optional().describe('Filter by state (default open).'),
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(50)
+ .optional()
+ .describe('How many issues to return per page, 1-50 (default 10).'),
+ page: z.number().int().min(1).optional().describe('Page number (default 1).'),
+ }),
+ execute: async (credential, input) => {
+ const query = new URLSearchParams({
+ state: input.state ? String(input.state) : 'open',
+ per_page: String(input.limit ?? 10),
+ page: String(input.page ?? 1),
+ });
+ const items = await githubRequest<GithubIssue[]>(
+ credential,
+ 'GET',
+ `${repoPath(input.owner, input.repo)}/issues?${query}`,
+ );
+ return {
+ issues: items
+ .filter((issue) => !issue.pull_request)
+ .map((issue) => ({
+ number: issue.number,
+ title: issue.title ?? '',
+ state: issue.state ?? null,
+ url: issue.html_url ?? null,
+ updatedAt: issue.updated_at ?? null,
+ labels: (issue.labels ?? []).map((label) =>
+ typeof label === 'string' ? label : (label.name ?? ''),
+ ),
+ })),
+ };
+ },
+};
diff --git a/packages/agent-tools/src/tools/github/update-discussion.ts b/packages/agent-tools/src/tools/github/update-discussion.ts
new file mode 100644
index 00000000..be2e5a38
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/update-discussion.ts
@@ -0,0 +1,67 @@
+import { z } from 'zod';
+import type { CustomToolEntry } from '../../types';
+import { discussionId, discussionInput, githubGraphql, repoInput } from './client';
+
+interface Discussion {
+ number: number;
+ closed: boolean;
+ url: string;
+}
+
+const FIELDS = 'discussion { number closed url }';
+
+// GitHub has one mutation for the edit and one each for closing and reopening, so a
+// call that does both sends two.
+export const githubUpdateDiscussion: CustomToolEntry = {
+ key: 'github_update_discussion',
+ label: 'GitHub Update Discussion',
+ description:
+ 'Update a discussion in a GitHub repository: change its title or markdown body, or close and reopen it. Give at least one of title, body or state.',
+ inputSchema: z.object({
+ ...repoInput,
+ discussion: discussionInput,
+ title: z.string().min(1).optional().describe('New title.'),
+ body: z.string().min(1).optional().describe('New text, as markdown.'),
+ state: z
+ .enum(['open', 'closed'])
+ .optional()
+ .describe('closed closes the discussion as resolved, open reopens it.'),
+ }),
+ execute: async (credential, input) => {
+ if (input.title === undefined && input.body === undefined && input.state === undefined) {
+ throw new Error('Give at least one of title, body or state to update.');
+ }
+ const id = await discussionId(credential, input.owner, input.repo, input.discussion);
+ let discussion: Discussion | undefined;
+ if (input.title !== undefined || input.body !== undefined) {
+ const data = await githubGraphql<{ updateDiscussion: { discussion: Discussion } }>(
+ credential,
+ `mutation($input: UpdateDiscussionInput!) { updateDiscussion(input: $input) { ${FIELDS} } }`,
+ {
+ input: {
+ discussionId: id,
+ ...(input.title !== undefined ? { title: String(input.title) } : {}),
+ ...(input.body !== undefined ? { body: String(input.body) } : {}),
+ },
+ },
+ );
+ discussion = data.updateDiscussion.discussion;
+ }
+ if (input.state === 'closed') {
+ const data = await githubGraphql<{ closeDiscussion: { discussion: Discussion } }>(
+ credential,
+ `mutation($input: CloseDiscussionInput!) { closeDiscussion(input: $input) { ${FIELDS} } }`,
+ { input: { discussionId: id, reason: 'RESOLVED' } },
+ );
+ discussion = data.closeDiscussion.discussion;
+ } else if (input.state === 'open') {
+ const data = await githubGraphql<{ reopenDiscussion: { discussion: Discussion } }>(
+ credential,
+ `mutation($input: ReopenDiscussionInput!) { reopenDiscussion(input: $input) { ${FIELDS} } }`,
+ { input: { discussionId: id } },
+ );
+ discussion = data.reopenDiscussion.discussion;
+ }
+ return discussion!;
+ },
+};
diff --git a/packages/agent-tools/src/tools/github/update-issue.ts b/packages/agent-tools/src/tools/github/update-issue.ts
new file mode 100644
index 00000000..cca583f1
--- /dev/null
+++ b/packages/agent-tools/src/tools/github/update-issue.ts
@@ -0,0 +1,47 @@
+import { z } from 'zod';
+import type { CustomToolEntry } from '../../types';
+import {
+ githubRequest,
+ issueInput,
+ numberRef,
+ repoInput,
+ repoPath,
+ type GithubIssue,
+} from './client';
+
+export const githubUpdateIssue: CustomToolEntry = {
+ key: 'github_update_issue',
+ label: 'GitHub Update Issue',
+ description:
+ 'Update an issue in a GitHub repository: change its title or markdown body, or close and reopen it. Give at least one of title, body or state.',
+ inputSchema: z.object({
+ ...repoInput,
+ issue: issueInput,
+ title: z.string().min(1).optional().describe('New title.'),
+ body: z.string().optional().describe('New description, as markdown.'),
+ state: z
+ .enum(['open', 'closed'])
+ .optional()
+ .describe('closed closes the issue, open reopens it.'),
+ }),
+ execute: async (credential, input) => {
+ if (input.title === undefined && input.body === undefined && input.state === undefined) {
+ throw new Error('Give at least one of title, body or state to update.');
+ }
+ const patch: Record<string, unknown> = {};
+ if (input.title !== undefined) patch.title = String(input.title);
+ if (input.body !== undefined) patch.body = String(input.body);
+ if (input.state !== undefined) patch.state = input.state;
+ const issue = await githubRequest<GithubIssue>(
+ credential,
+ 'PATCH',
+ `${repoPath(input.owner, input.repo)}/issues/${numberRef(input.issue, 'issue')}`,
+ patch,
+ );
+ return {
+ number: issue.number,
+ state: issue.state ?? null,
+ url: issue.html_url ?? null,
+ };
+ },
+};