Skip to content

g1t/apps/api/src/tools.rs

871 lines48,300 bytesCodeBlame
1//! The MCP server's tools: a few resource tools, each with an `action`.
2//!
3//! Every operation is one action of one tool. A call is dispatched to the
4//! operation it names, so permissions, the audit log, billing and outcomes
5//! are exactly those of the REST API. A token sees only the actions its
6//! scopes allow, and a tool none of whose actions it may use is not listed.
7//!
8//! The listed input schema is one flat object: `action`, then every field
9//! any of its actions takes. Which fields each action needs is in the
10//! `action` field's description and checked on every call. Claude's API,
11//! and so most MCP clients, refuse a tool whose input schema has `oneOf`
12//! at its top level, so the schema keyed by action, with each action's
13//! required fields, is [`discriminated`], published on the server's card
14//! and in the docs.
15
16use g1t_contracts::credentials::NEVER;
17use g1t_contracts::identity::AgentScope;
18use g1t_contracts::scopes::{Level, NO_SCOPE, TokenAccess, scope_for};
19use serde_json::{Map, Value, json};
20
21use crate::operations::Op;
22use crate::security::SecurityOp;
23
24pub struct Action {
25 pub name: &'static str,
26 pub op: Op,
27 /// One line, for the `action` field's description.
28 pub summary: &'static str,
29}
30
31pub struct Tool {
32 pub name: &'static str,
33 pub title: &'static str,
34 /// What it is for, in a sentence or two.
35 pub description: &'static str,
36 pub actions: &'static [Action],
37 /// The action a call without one runs.
38 pub default_action: Option<&'static str>,
39}
40
41const fn a(name: &'static str, op: Op, summary: &'static str) -> Action {
42 Action { name, op, summary }
43}
44
45pub const TOOLS: &[Tool] = &[
46 Tool {
47 name: "search",
48 title: "Search",
49 description: "Find things. `code` (the default) searches all of g1t you can see: repositories, code, issues, pull requests and people, with qualifiers like repo:owner/name, language:rust, is:issue. `context` searches one workspace's catalog, docs, issues and memory by meaning.",
50 default_action: Some("code"),
51 actions: &[
52 a("code", Op::Search, "Search all of g1t: repositories, code, issues, pull requests, people"),
53 a("context", Op::SearchContext, "Search a workspace's context hub by meaning"),
54 a("entity", Op::GetEntity, "One catalog entry and its relations"),
55 a("ticket", Op::GetContext, "A Jira, Linear or Sentry item the work refers to, as it is now"),
56 ],
57 },
58 Tool {
59 name: "repository",
60 title: "Repositories",
61 description: "Repositories: find, read and create them, change their settings, check their CODEOWNERS file, manage their labels and milestones, and see and dismiss their security alerts (secrets and vulnerable dependencies). Name one as \"owner/name\". Deleting, transferring and changing visibility need `confirm`.",
62 default_action: None,
63 actions: &[
64 a("list", Op::ListRepos, "Repositories you can see"),
65 a("get", Op::GetRepo, "One repository"),
66 a("create", Op::CreateRepo, "Create one, empty or copied from a public git URL"),
67 a("update", Op::UpdateRepo, "Change description, website, topics, default branch, protection"),
68 a("get_settings", Op::GetRepoSettings, "Branch protection: required checks, approvals, how pull requests merge"),
69 a("update_settings", Op::UpdateRepoSettings, "Change branch protection and how pull requests merge"),
70 a("check_names", Op::ListCheckNames, "Check names reported lately, to require on the default branch"),
71 a("codeowners", Op::GetCodeownersErrors, "Problems in its CODEOWNERS file, by line"),
72 a("list_labels", Op::ListLabels, "Labels, with colors and how many issues and pull requests carry each"),
73 a("create_label", Op::CreateLabel, "Create a label"),
74 a("update_label", Op::UpdateLabel, "Rename a label or change its color or description"),
75 a("delete_label", Op::DeleteLabel, "Delete a label, from everything that carries it"),
76 a("add_default_labels", Op::AddDefaultLabels, "Add the default labels it is missing"),
77 a("list_milestones", Op::ListMilestones, "Milestones, with progress and due dates"),
78 a("get_milestone", Op::GetMilestone, "One milestone with its issues and pull requests"),
79 a("create_milestone", Op::CreateMilestone, "Create a milestone"),
80 a("update_milestone", Op::UpdateMilestone, "Change a milestone's title, description, due date or state"),
81 a("delete_milestone", Op::DeleteMilestone, "Delete a milestone"),
82 a("list_events", Op::ListEvents, "Timeline: pushes, issues, pull requests, comments"),
83 a("rename_branch", Op::RenameBranch, "Rename a branch"),
84 a("rename", Op::RenameRepo, "Rename it; old addresses redirect"),
85 a("transfer", Op::TransferRepo, "Move it to another workspace you own"),
86 a("archive", Op::ArchiveRepo, "Make it read-only"),
87 a("unarchive", Op::UnarchiveRepo, "Make it writable again"),
88 a("set_visibility", Op::SetRepoVisibility, "Make it public or private"),
89 a("delete", Op::DeleteRepo, "Delete it; restorable for 30 days"),
90 a("list_deleted", Op::ListDeletedRepos, "A workspace's deleted repositories"),
91 a("restore", Op::RestoreRepo, "Restore a deleted one"),
92 a("purge", Op::PurgeRepo, "Remove a deleted one for good"),
93 a("security_alerts", Op::ListSecurityAlerts, "Secret and dependency alerts, filtered by state"),
94 a("dismiss_alert", Op::DismissSecurityAlert, "Dismiss an alert with a reason"),
95 a("reopen_alert", Op::ReopenSecurityAlert, "Reopen a dismissed alert"),
96 ],
97 },
98 Tool {
99 name: "issue",
100 title: "Issues",
101 description: "Issues: what should change. Read one before working on it to see the pull requests already made for it. Issues and pull requests share numbers; `comment` works on either.",
102 default_action: None,
103 actions: &[
104 a("list", Op::ListIssues, "Issues on a repository, newest first"),
105 a("get", Op::GetIssue, "One issue with comments and its pull requests"),
106 a("create", Op::CreateIssue, "Open an issue"),
107 a("update", Op::UpdateIssue, "Change title, body, labels, milestone or assignees"),
108 a("labels", Op::ListIssueLabels, "The labels an issue or pull request carries"),
109 a("add_labels", Op::AddIssueLabels, "Add labels to an issue or pull request"),
110 a("set_labels", Op::SetIssueLabels, "Replace the labels of an issue or pull request"),
111 a("remove_labels", Op::RemoveIssueLabels, "Take labels off an issue or pull request"),
112 a("close", Op::CloseIssue, "Close it without a pull request"),
113 a("reopen", Op::ReopenIssue, "Reopen it"),
114 a("comment", Op::AddComment, "Comment on an issue or pull request; path and line for one line of a change"),
115 a("import", Op::ImportIssue, "Open an issue from a Jira, Linear or Sentry item"),
116 ],
117 },
118 Tool {
119 name: "pull_request",
120 title: "Pull requests",
121 description: "Pull requests: start a change for an issue, record your session, mark it ready, ask people and teams to review, review and merge. Read `overlaps` and `behind` on `get` before going far, and `code_owners` for whose approval it needs.",
122 default_action: None,
123 actions: &[
124 a("list", Op::ListPullRequests, "Pull requests on a repository, newest first"),
125 a("get", Op::GetPullRequest, "Status, checks and required checks, reviews, overlaps, whether it is behind"),
126 a("changes", Op::GetPullRequestChanges, "Files and line-by-line diff"),
127 a("create", Op::CreatePullRequest, "Start a draft with its own fork to push to, or open one from a pushed branch"),
128 a("update", Op::UpdatePullRequest, "Change its base branch, labels, milestone, assignees or reviewers"),
129 a("record_session", Op::RecordSession, "Append prompt, reasoning and tool entries to its session"),
130 a("read_session", Op::ReadSession, "Its recorded session"),
131 a("ready", Op::MarkPullRequestReady, "Mark a draft ready, with a summary"),
132 a("request_reviewers", Op::RequestReviewers, "Ask people or teams to review it"),
133 a("remove_requested_reviewers", Op::RemoveRequestedReviewers, "Stop asking people or teams to review it"),
134 a("review", Op::ReviewPullRequest, "Approve or request changes"),
135 a("close", Op::ClosePullRequest, "Close without merging"),
136 a("merge", Op::MergePullRequest, "Land it, or join the merge queue"),
137 a("merge_queue", Op::GetMergeQueue, "The repository's merge queue"),
138 ],
139 },
140 Tool {
141 name: "agent",
142 title: "g1t agents",
143 description: "Put g1t's agent to work and talk to it. One agent per issue; to do more at once, use more issues. Starting an agent uses the workspace's money.",
144 default_action: None,
145 actions: &[
146 a("delegate", Op::Delegate, "Open an issue and put an agent on it in one step"),
147 a("assign", Op::AssignIssue, "Put an agent on an existing issue"),
148 a("message", Op::MessageAgent, "Tell the agent on a pull request something, or ask another agent"),
149 a("answer", Op::AnswerMessage, "Answer a question or handoff sent to you"),
150 a("take_messages", Op::TakeMessages, "For a g1t agent: messages not seen yet"),
151 ],
152 },
153 Tool {
154 name: "plan",
155 title: "Plans",
156 description: "Turn an outcome into issues: an agent proposes them with what done means and their dependencies; nothing opens until you apply the plan.",
157 default_action: None,
158 actions: &[
159 a("create", Op::PlanWork, "Ask an agent for a plan; read it with get until ready"),
160 a("get", Op::GetPlan, "A plan and the issues it proposes"),
161 a("apply", Op::ApplyPlan, "Open its issues; with assign, agents start in dependency order"),
162 ],
163 },
164 Tool {
165 name: "memory",
166 title: "Memory",
167 description: "What the project and its workspace remember for the next agent: how to build, conventions, decisions, traps. Recall before you start; remember one short fact at a time, never a secret.",
168 default_action: None,
169 actions: &[
170 a("recall", Op::Recall, "Search memory, or list it all"),
171 a("remember", Op::Remember, "Save one fact"),
172 ],
173 },
174 Tool {
175 name: "workflow",
176 title: "Workflows",
177 description: "GitHub Actions workflows from .g1t/workflows: their runs, jobs and logs, and running, cancelling or rerunning them. Also the self-hosted runners they run on: a workspace's (`workspace`) or a repository's own (`repo`), their groups, and where agent work runs.",
178 default_action: None,
179 actions: &[
180 a("list", Op::ListWorkflows, "Workflows on the default branch"),
181 a("list_runs", Op::ListWorkflowRuns, "Runs, newest first"),
182 a("get_run", Op::GetWorkflowRun, "One run with its jobs and steps"),
183 a("job_logs", Op::GetJobLogs, "A job's log after a sequence number"),
184 a("dispatch", Op::DispatchWorkflow, "Run a workflow_dispatch workflow"),
185 a("cancel", Op::CancelWorkflowRun, "Cancel a run"),
186 a("rerun", Op::RerunWorkflowRun, "Run a finished run again"),
187 a("update", Op::UpdateWorkflow, "Turn a workflow on or off"),
188 a("list_runners", Op::ListRunners, "Self-hosted runners, with status, labels and what each is doing"),
189 a("create_runner_token", Op::CreateRunnerRegistrationToken, "A one-hour token for g1t-runner register"),
190 a("remove_runner", Op::RemoveRunner, "Remove a self-hosted runner"),
191 a("list_runner_groups", Op::ListRunnerGroups, "A workspace's runner groups"),
192 a("create_runner_group", Op::CreateRunnerGroup, "Make a group, for some repositories"),
193 a("update_runner_group", Op::UpdateRunnerGroup, "Rename a group or change its repositories"),
194 a("delete_runner_group", Op::DeleteRunnerGroup, "Delete a group; its runners join the default"),
195 a("get_runner_settings", Op::GetRunnerSettings, "Where agent work runs; whether forks may use runners"),
196 a("update_runner_settings", Op::UpdateRunnerSettings, "Change them"),
197 ],
198 },
199 Tool {
200 name: "secret",
201 title: "Secrets and variables",
202 description: "A repository's or workspace's secrets and variables, read by workflows and deployments. Secret values are never returned.",
203 default_action: None,
204 actions: &[
205 a("list_secrets", Op::ListActionsSecrets, "Secrets, without values"),
206 a("set_secret", Op::SetActionsSecret, "Add or change a secret"),
207 a("delete_secret", Op::DeleteActionsSecret, "Remove a secret"),
208 a("list_variables", Op::ListActionsVariables, "Variables, with values"),
209 a("set_variable", Op::SetActionsVariable, "Add or change a variable"),
210 a("delete_variable", Op::DeleteActionsVariable, "Remove a variable"),
211 ],
212 },
213 Tool {
214 name: "webhook",
215 title: "Webhooks",
216 description: "HTTPS addresses sent signed events as they happen, for a repository or a whole workspace.",
217 default_action: None,
218 actions: &[
219 a("list", Op::ListWebhooks, "Webhooks, without secrets"),
220 a("create", Op::CreateWebhook, "Register one; a ping is sent"),
221 a("update", Op::UpdateWebhook, "Change address, events or active"),
222 a("delete", Op::DeleteWebhook, "Remove one"),
223 a("ping", Op::PingWebhook, "Send a ping"),
224 a("list_deliveries", Op::ListWebhookDeliveries, "Latest deliveries"),
225 a("redeliver", Op::RedeliverWebhook, "Send a delivery again"),
226 ],
227 },
228 Tool {
229 name: "access",
230 title: "Who has access",
231 description: "Who has access to a repository and with which role (read, triage, write, maintain, admin), outside collaborators, and a workspace's base permission.",
232 default_action: None,
233 actions: &[
234 a("list_collaborators", Op::ListCollaborators, "Everyone with a role, and pending invitations"),
235 a("get_permission", Op::GetCollaboratorPermission, "One person's role and capabilities"),
236 a("add_collaborator", Op::AddCollaborator, "Give someone a role, by username or email"),
237 a("update_collaborator", Op::UpdateCollaborator, "Change a direct role"),
238 a("remove_collaborator", Op::RemoveCollaborator, "Take away a direct role"),
239 a("list_invitations", Op::ListRepoInvitations, "Pending invitations to a repository"),
240 a("revoke_invitation", Op::RevokeRepoInvitation, "Withdraw one"),
241 a("set_base_permission", Op::SetBasePermission, "What every member gets on each repository"),
242 a("list_outside_collaborators", Op::ListOutsideCollaborators, "People with roles who are not members"),
243 ],
244 },
245 Tool {
246 name: "team",
247 title: "Teams",
248 description: "Teams: groups of a workspace's members, given roles on repositories together, mentioned as @workspace/team and asked to review together. Name one by `workspace` and its slug (`team`). Any member may create a team; the workspace's owners and the team's maintainers manage it. A secret team is seen only by its people and the owners.",
249 default_action: None,
250 actions: &[
251 a("list", Op::ListTeams, "A workspace's teams you can see"),
252 a("get", Op::GetTeam, "One team"),
253 a("create", Op::CreateTeam, "Create a team; you become its maintainer"),
254 a("update", Op::UpdateTeam, "Change its name, slug, description, visibility, parent or notifications"),
255 a("delete", Op::DeleteTeam, "Delete it; its child teams move up"),
256 a("list_members", Op::ListTeamMembers, "Its people and their roles, child teams' with include_child_teams"),
257 a("set_member", Op::SetTeamMember, "Add a member of the workspace, or change their role"),
258 a("remove_member", Op::RemoveTeamMember, "Take someone out of it"),
259 a("list_child_teams", Op::ListChildTeams, "The teams nested under it"),
260 a("list_repos", Op::ListTeamRepos, "The repositories it has a role on"),
261 a("set_repo", Op::SetTeamRepo, "Give it a role on a repository"),
262 a("remove_repo", Op::RemoveTeamRepo, "Take its role on a repository away"),
263 a("set_review_assignment", Op::SetTeamReviewAssignment, "Whom it picks when asked to review"),
264 a("list_user_teams", Op::ListUserTeams, "The teams someone is in"),
265 ],
266 },
267 Tool {
268 name: "workspace",
269 title: "Workspaces",
270 description: "Workspaces own repositories (g1t.sh/{workspace}/{repo}): create, update or delete one, invite members, connect integrations and model providers, and keep your own pinned projects at the top of its sidebar.",
271 default_action: None,
272 actions: &[
273 a("create", Op::CreateWorkspace, "Create a workspace"),
274 a("delete", Op::DeleteWorkspace, "Delete a workspace and everything in it (support can restore it for 30 days)"),
275 a("update", Op::UpdateWorkspace, "Change its name, description or base permission"),
276 a("list_invites", Op::ListWorkspaceInvites, "Its invites"),
277 a("invite_member", Op::InviteMember, "Invite an email address"),
278 a("revoke_invite", Op::RevokeWorkspaceInvite, "Revoke a pending invite"),
279 a("list_integrations", Op::ListIntegrations, "Model providers, alert sources, trackers"),
280 a("connect_integration", Op::ConnectIntegration, "Connect one"),
281 a("disconnect_integration", Op::DisconnectIntegration, "Remove one"),
282 a("test_integration", Op::TestIntegration, "Check its credentials"),
283 a("get_model_routes", Op::GetModelRoutes, "Where each kind of work's model requests go"),
284 a("set_model_routes", Op::SetModelRoutes, "Replace them"),
285 a("list_pinned_projects", Op::ListPinnedProjects, "Your pinned projects in it, in your order"),
286 a("pin_project", Op::PinProject, "Pin a project, at a position or the end"),
287 a("unpin_project", Op::UnpinProject, "Unpin a project"),
288 a("reorder_pinned_projects", Op::ReorderPinnedProjects, "Put your pins in a new order"),
289 ],
290 },
291 Tool {
292 name: "billing",
293 title: "Billing",
294 description: "A workspace's billing: its usage by product, project and day, its budget (the monthly spend limit, alerts and whether usage pauses at it), its AI credit, and its invoices. Amounts are whole millionths of a dollar (`_micros`), or cents (`_cents`) where named. Members read it; changing the budget and buying credit are for owners, as people, and never for g1t's agents.",
295 default_action: Some("usage"),
296 actions: &[
297 a("usage", Op::GetUsage, "Usage over a range of days, by product, meter, project and day, and what paid for it"),
298 a("budget", Op::GetBudget, "The monthly spend limit, what was spent, alerts and whether usage pauses at the limit"),
299 a("set_budget", Op::SetBudget, "Change the spend limit, alerts, pausing or the alert webhook"),
300 a("ai_credit", Op::GetAiCredit, "AI credit left, its grants, auto-reload and how to buy more"),
301 a("buy_ai_credit", Op::BuyAiCredit, "A payment page to buy AI credit, for a person to open"),
302 a("invoices", Op::ListInvoices, "Every invoice, the itemised usage invoices, and the next one so far"),
303 a("billing_details", Op::GetBillingDetails, "Who invoices are made out to and the payment method on file"),
304 ],
305 },
306 Tool {
307 name: "security",
308 title: "Security",
309 description: "A repository's security: secret scanning alerts and push protection bypasses, custom secret patterns, code scanning alerts and SARIF uploads, vulnerability alerts, the dependency graph and its SBOM, dependency review, settings, and a workspace's overview. Fix an alert with g1t. Findings are shown to those who can change the code only. Give `repo` (owner/name), or `workspace` for lists across one.",
310 default_action: Some("secret_alerts"),
311 actions: &[
312 a("secret_alerts", Op::Security(SecurityOp::ListSecretAlerts), "Secret scanning alerts; by state, secret_type, validity, bypassed"),
313 a("secret_alert", Op::Security(SecurityOp::GetSecretAlert), "One secret alert, with where it was found and its bypass requests"),
314 a("update_secret_alert", Op::Security(SecurityOp::UpdateSecretAlert), "Dismiss a secret alert with a reason, or reopen it"),
315 a("secret_locations", Op::Security(SecurityOp::ListSecretLocations), "Every file, line and commit a secret is in"),
316 a("bypass", Op::Security(SecurityOp::BypassPushProtection), "Push past push protection with a reason, or ask to"),
317 a("check_validity", Op::Security(SecurityOp::CheckSecretValidity), "Ask a secret's issuer whether it still works"),
318 a("bypass_requests", Op::Security(SecurityOp::ListBypassRequests), "A workspace's push protection bypass requests"),
319 a("review_bypass", Op::Security(SecurityOp::ReviewBypassRequest), "Approve, deny or cancel a bypass request"),
320 a("patterns", Op::Security(SecurityOp::ListCustomPatterns), "Custom secret patterns of a repository or workspace"),
321 a("create_pattern", Op::Security(SecurityOp::CreateCustomPattern), "Create a custom secret pattern, as a draft or published"),
322 a("update_pattern", Op::Security(SecurityOp::UpdateCustomPattern), "Change, publish or unpublish a custom pattern"),
323 a("delete_pattern", Op::Security(SecurityOp::DeleteCustomPattern), "Delete a custom pattern"),
324 a("dry_run_pattern", Op::Security(SecurityOp::DryRunCustomPattern), "Run a pattern over the default branch without saving it"),
325 a("code_alerts", Op::Security(SecurityOp::ListCodeAlerts), "Code scanning alerts; by state, severity, tool, rule_id"),
326 a("code_alert", Op::Security(SecurityOp::GetCodeAlert), "One code scanning alert by number"),
327 a("update_code_alert", Op::Security(SecurityOp::UpdateCodeAlert), "Dismiss a code scanning alert with a reason, or reopen it"),
328 a("analyses", Op::Security(SecurityOp::ListAnalyses), "Code scanning analyses, newest first"),
329 a("upload_sarif", Op::Security(SecurityOp::UploadSarif), "Upload a SARIF file, gzipped and base64-encoded"),
330 a("sarif_upload", Op::Security(SecurityOp::GetSarifUpload), "Whether a SARIF upload was read, and its analyses"),
331 a("vulnerability_alerts", Op::Security(SecurityOp::ListVulnerabilityAlerts), "Vulnerable dependencies; by state, severity, ecosystem, package"),
332 a("vulnerability_alert", Op::Security(SecurityOp::GetVulnerabilityAlert), "One vulnerability alert"),
333 a("update_vulnerability_alert", Op::Security(SecurityOp::UpdateVulnerabilityAlert), "Dismiss a vulnerability alert with a reason, or reopen it"),
334 a("fix", Op::Security(SecurityOp::FixAlert), "Put g1t on an issue to fix an alert"),
335 a("dependency_graph", Op::Security(SecurityOp::GetDependencyGraph), "Every package the lockfiles resolve, direct or transitive"),
336 a("sbom", Op::Security(SecurityOp::GetSbom), "The dependency graph as an SPDX 2.3 document"),
337 a("compare_dependencies", Op::Security(SecurityOp::CompareDependencies), "What changes in dependencies between base...head"),
338 a("settings", Op::Security(SecurityOp::GetSettings), "A repository's security settings"),
339 a("update_settings", Op::Security(SecurityOp::UpdateSettings), "Change when checks fail and dependency review's policy"),
340 a("workspace_settings", Op::Security(SecurityOp::GetWorkspaceSettings), "A workspace's delegated bypass and validity checks"),
341 a("update_workspace_settings", Op::Security(SecurityOp::UpdateWorkspaceSettings), "Turn delegated bypass or validity checks on or off"),
342 a("overview", Op::Security(SecurityOp::GetOverview), "A workspace's alerts, trends and coverage"),
343 ],
344 },
345 Tool {
346 name: "notifications",
347 title: "Notifications",
348 description: "Your inbox: what needs you, and what you follow. One thread per issue, pull request, workflow or deployment, with why you were told (`reason`): an agent waiting on you, a review asked of you, an assignment, a mention, your work's checks, or what you subscribe to and watch. Mark threads read or done once handled, and choose what you hear of with subscribe, unsubscribe and watch. Your own: a personal token.",
349 default_action: Some("list"),
350 actions: &[
351 a("list", Op::ListNotifications, "Unread threads, latest first; all, a view, a reason, a repository"),
352 a("get", Op::GetNotificationThread, "One thread with its recent activity and your subscription"),
353 a("mark_read", Op::MarkThreadRead, "Mark a thread read, or unread"),
354 a("mark_all_read", Op::MarkNotificationsRead, "Mark everything read up to a time, or one repository's"),
355 a("done", Op::MarkThreadDone, "Mark a thread done; new activity brings it back"),
356 a("save", Op::SaveThread, "Save a thread, or unsave it"),
357 a("snooze", Op::SnoozeThread, "Snooze a thread until a time, or bring it back"),
358 a("subscription", Op::GetThreadSubscription, "Your subscription to an issue or pull request"),
359 a("subscribe", Op::SetThreadSubscription, "Subscribe to an issue or pull request, or ignore it"),
360 a("unsubscribe", Op::DeleteThreadSubscription, "Unsubscribe until you comment or are mentioned"),
361 a("watching", Op::GetRepoSubscription, "How you watch a repository"),
362 a("watch", Op::SetRepoSubscription, "Watch a repository: participating, all, ignore or custom"),
363 a("unwatch", Op::DeleteRepoSubscription, "Stop watching a repository"),
364 a("watched", Op::ListWatchedRepos, "Repositories you watch other than the default way"),
365 ],
366 },
367 Tool {
368 name: "account",
369 title: "Your account",
370 description: "Who this token acts as and its workspaces (`whoami`), your email addresses, your invites, and invitations to repositories waiting for you.",
371 default_action: Some("whoami"),
372 actions: &[
373 a("whoami", Op::Whoami, "Who the token acts as, and its workspaces"),
374 a("list_emails", Op::ListEmails, "Your addresses"),
375 a("add_email", Op::AddEmail, "Add an address"),
376 a("remove_email", Op::RemoveEmail, "Remove an address"),
377 a("update_email_settings", Op::UpdateEmailSettings, "Primary, backup and privacy"),
378 a("list_invites", Op::ListInvites, "Your invites to g1t"),
379 a("create_invite", Op::CreateInvite, "Make an invite"),
380 a("revoke_invite", Op::RevokeInvite, "Revoke one"),
381 a("list_repository_invitations", Op::ListMyRepoInvitations, "Invitations to repositories for you"),
382 a("accept_repository_invitation", Op::AcceptRepoInvitation, "Accept one"),
383 a("decline_repository_invitation", Op::DeclineRepoInvitation, "Decline one"),
384 ],
385 },
386];
387
388/// Operations that cannot be undone, or reach beyond g1t's own records:
389/// clients ask before running a tool that has any of them.
390fn destructive(op: Op) -> bool {
391 matches!(
392 op,
393 Op::Security(SecurityOp::DeleteCustomPattern | SecurityOp::BypassPushProtection)
394 | Op::DeleteWorkspace
395 | Op::UpdateWorkspace
396 | Op::DeleteRepo
397 | Op::PurgeRepo
398 | Op::TransferRepo
399 | Op::SetRepoVisibility
400 | Op::RemoveEmail
401 | Op::RemoveCollaborator
402 | Op::DisconnectIntegration
403 | Op::DeleteWebhook
404 | Op::DeleteActionsSecret
405 | Op::DeleteActionsVariable
406 | Op::SetActionsSecret
407 | Op::SetActionsVariable
408 | Op::SetModelRoutes
409 | Op::SetBasePermission
410 | Op::DeleteTeam
411 | Op::RemoveTeamRepo
412 | Op::MergePullRequest
413 | Op::RemoveRunner
414 | Op::DeleteRunnerGroup
415 | Op::UpdateRunnerSettings
416 )
417}
418
419/// Whether an operation only reads.
420pub fn reads_only(op: Op) -> bool {
421 NO_SCOPE.contains(&op.name())
422 || scope_for(op.name()).is_some_and(|scope| scope.level() == Level::Read)
423}
424
425/// What decides which actions a caller sees.
426pub enum Gate<'a> {
427 /// No limit beyond the person's own role.
428 Everything,
429 /// A g1t agent's token: the operations its run lists.
430 Agent(&'a AgentScope),
431 /// An access token with scopes.
432 Token(&'a TokenAccess),
433}
434
435impl Gate<'_> {
436 pub fn allows(&self, op: Op) -> bool {
437 match self {
438 Gate::Everything => true,
439 Gate::Agent(scope) => op.allowed_by(scope) && !NEVER.contains(&op.name()),
440 Gate::Token(access) => {
441 if NO_SCOPE.contains(&op.name()) {
442 return true;
443 }
444 match scope_for(op.name()) {
445 Some(scope) => access.allows(scope),
446 None => access.scopes.is_none(),
447 }
448 }
449 }
450 }
451}
452
453impl Tool {
454 pub fn by_name(name: &str) -> Option<&'static Tool> {
455 TOOLS.iter().find(|tool| tool.name == name)
456 }
457
458 pub fn action(&self, name: &str) -> Option<&'static Action> {
459 // The tools are 'static; find through TOOLS to keep the lifetime.
460 TOOLS
461 .iter()
462 .find(|tool| tool.name == self.name)
463 .and_then(|tool| tool.actions.iter().find(|action| action.name == name))
464 }
465
466 pub fn visible(&self, gate: &Gate) -> Vec<&'static Action> {
467 TOOLS
468 .iter()
469 .find(|tool| tool.name == self.name)
470 .map(|tool| tool.actions.iter().filter(|action| gate.allows(action.op)).collect())
471 .unwrap_or_default()
472 }
473
474 /// The flat input schema of the actions given.
475 pub fn input_schema(&self, actions: &[&Action]) -> Value {
476 let mut properties = Map::new();
477 let lines: Vec<String> = actions
478 .iter()
479 .map(|action| {
480 let required: Vec<String> = action.op.required();
481 if required.is_empty() {
482 format!("{}: {}.", action.name, action.summary)
483 } else {
484 format!("{} ({}): {}.", action.name, required.join(", "), action.summary)
485 }
486 })
487 .collect();
488 let mut action_schema = json!({
489 "type": "string",
490 "enum": actions.iter().map(|action| action.name).collect::<Vec<_>>(),
491 "description": lines.join("\n"),
492 });
493 if let Some(default) = self.default_action.filter(|name| actions.iter().any(|action| action.name == *name)) {
494 action_schema["default"] = json!(default);
495 }
496 properties.insert("action".to_owned(), action_schema);
497 for action in actions {
498 for (name, schema) in action.op.properties() {
499 merge_property(&mut properties, name, schema);
500 }
501 }
502 let mut required = vec![];
503 if self.default_action.is_none() {
504 required.push("action");
505 }
506 let mut schema = json!({ "type": "object", "properties": properties });
507 if !required.is_empty() {
508 schema["required"] = json!(required);
509 }
510 schema
511 }
512
513 /// The input schema keyed by action: one `oneOf` branch per action,
514 /// each with its own fields and the ones it needs.
515 pub fn discriminated(&self, actions: &[&Action]) -> Value {
516 let branches: Vec<Value> = actions
517 .iter()
518 .map(|action| {
519 let mut properties = Map::new();
520 properties.insert("action".to_owned(), json!({ "const": action.name }));
521 properties.extend(action.op.properties());
522 let mut required = vec![Value::String("action".to_owned())];
523 // The default action may leave `action` out.
524 if self.default_action == Some(action.name) {
525 required.clear();
526 }
527 required.extend(action.op.required().into_iter().map(Value::String));
528 json!({
529 "title": action.name,
530 "description": action.summary,
531 "type": "object",
532 "properties": properties,
533 "required": required,
534 })
535 })
536 .collect();
537 json!({ "type": "object", "oneOf": branches })
538 }
539
540 /// MCP's hints about the actions given: whether the tool only reads,
541 /// whether it can destroy something, and whether calling it twice is
542 /// the same as once.
543 pub fn annotations(&self, actions: &[&Action]) -> Value {
544 let read_only = actions.iter().all(|action| reads_only(action.op));
545 json!({
546 "title": self.title,
547 "readOnlyHint": read_only,
548 "destructiveHint": !read_only && actions.iter().any(|action| destructive(action.op)),
549 "idempotentHint": read_only,
550 "openWorldHint": false,
551 })
552 }
553
554 /// The tool as `tools/list` gives it, for a caller behind `gate`, or
555 /// `None` when it may use none of its actions.
556 pub fn listed(&self, gate: &Gate) -> Option<Value> {
557 let actions = self.visible(gate);
558 if actions.is_empty() {
559 return None;
560 }
561 Some(json!({
562 "name": self.name,
563 "title": self.title,
564 "description": self.description,
565 "inputSchema": self.input_schema(&actions),
566 "annotations": self.annotations(&actions),
567 }))
568 }
569}
570
571/// Adds a property to a tool's flat schema. The first action to use a name
572/// describes it; a later one with other allowed values adds them.
573fn merge_property(properties: &mut Map<String, Value>, name: String, schema: Value) {
574 match properties.get_mut(&name) {
575 None => {
576 properties.insert(name, schema);
577 }
578 Some(existing) => {
579 if let (Some(Value::Array(had)), Some(Value::Array(more))) =
580 (existing.get("enum").cloned(), schema.get("enum"))
581 {
582 let mut merged = had;
583 for value in more {
584 if !merged.contains(value) {
585 merged.push(value.clone());
586 }
587 }
588 existing["enum"] = Value::Array(merged);
589 }
590 // Different kinds of value under one name: say less, accept both.
591 if existing.get("type") != schema.get("type")
592 && let Some(fields) = existing.as_object_mut()
593 {
594 fields.remove("type");
595 fields.remove("items");
596 }
597 }
598 }
599}
600
601/// What a call to a tool runs: the operation its action names, or why not.
602pub fn resolve(tool: &Tool, arguments: &Value) -> Result<Op, String> {
603 let names = || {
604 tool.actions
605 .iter()
606 .map(|action| action.name)
607 .collect::<Vec<_>>()
608 .join(", ")
609 };
610 let Some(name) = arguments["action"].as_str().or(tool.default_action) else {
611 return Err(format!("Give an action: one of {}.", names()));
612 };
613 let Some(action) = tool.action(name) else {
614 return Err(format!("{} has no action {name}. Its actions: {}.", tool.name, names()));
615 };
616 let missing: Vec<String> = action
617 .op
618 .required()
619 .into_iter()
620 .filter(|field| arguments.get(field).is_none_or(Value::is_null))
621 .collect();
622 if !missing.is_empty() {
623 return Err(format!("{}.{name} needs {}.", tool.name, missing.join(", ")));
624 }
625 Ok(action.op)
626}
627
628#[cfg(test)]
629mod tests {
630 use super::*;
631 use g1t_contracts::scopes::{Preset, Scope};
632
633 fn listed(gate: &Gate) -> Vec<Value> {
634 TOOLS.iter().filter_map(|tool| tool.listed(gate)).collect()
635 }
636
637 fn token(scopes: Option<Vec<Scope>>) -> TokenAccess {
638 TokenAccess {
639 token_id: "tok_1".to_owned(),
640 scopes: scopes.map(|scopes| scopes.iter().map(|scope| scope.as_str().to_owned()).collect()),
641 legacy: false,
642 }
643 }
644
645 #[test]
646 fn every_operation_is_exactly_one_action_of_one_tool() {
647 for op in Op::ALL {
648 let count = TOOLS
649 .iter()
650 .flat_map(|tool| tool.actions.iter())
651 .filter(|action| action.op == op)
652 .count();
653 assert_eq!(count, 1, "{} is {count} actions", op.name());
654 }
655 for tool in TOOLS {
656 let mut names = std::collections::HashSet::new();
657 for action in tool.actions {
658 assert!(names.insert(action.name), "{}.{} twice", tool.name, action.name);
659 }
660 if let Some(default) = tool.default_action {
661 assert!(tool.action(default).is_some(), "{}", tool.name);
662 }
663 }
664 assert!(TOOLS.len() <= 17, "{} tools", TOOLS.len());
665 }
666
667 #[test]
668 fn every_operation_needs_exactly_one_scope_or_none() {
669 use g1t_contracts::scopes::OPERATIONS;
670 for op in Op::ALL {
671 let mapped = OPERATIONS.iter().filter(|(name, _)| *name == op.name()).count();
672 let free = NO_SCOPE.contains(&op.name());
673 assert_eq!(mapped + usize::from(free), 1, "{}", op.name());
674 }
675 for (name, _) in OPERATIONS {
676 assert!(Op::by_name(name).is_some(), "{name} is not an operation");
677 }
678 }
679
680 #[test]
681 fn each_tool_schema_is_valid_with_one_branch_per_action() {
682 for tool in TOOLS {
683 let actions: Vec<&Action> = tool.actions.iter().collect();
684 let flat = tool.input_schema(&actions);
685 assert_eq!(flat["type"], "object");
686 assert!(flat.get("oneOf").is_none(), "no oneOf at the top level");
687 let listed: Vec<&str> = flat["properties"]["action"]["enum"]
688 .as_array()
689 .unwrap()
690 .iter()
691 .map(|name| name.as_str().unwrap())
692 .collect();
693 assert_eq!(listed, tool.actions.iter().map(|action| action.name).collect::<Vec<_>>());
694 for action in tool.actions {
695 for field in action.op.required() {
696 assert!(flat["properties"].get(&field).is_some(), "{}.{}: {field}", tool.name, action.name);
697 }
698 }
699 let keyed = tool.discriminated(&actions);
700 let branches = keyed["oneOf"].as_array().unwrap();
701 assert_eq!(branches.len(), tool.actions.len());
702 for (branch, action) in branches.iter().zip(tool.actions) {
703 assert_eq!(branch["properties"]["action"]["const"], action.name);
704 for field in branch["required"].as_array().unwrap() {
705 assert!(branch["properties"].get(field.as_str().unwrap()).is_some(), "{}.{}: {field}", tool.name, action.name);
706 }
707 }
708 // A well-formed JSON Schema object throughout.
709 let text = serde_json::to_string(&flat).unwrap();
710 assert!(serde_json::from_str::<Value>(&text).is_ok());
711 }
712 }
713
714 #[test]
715 fn a_read_only_token_sees_read_actions_only() {
716 let access = token(Preset::ReadOnly.scopes());
717 let gate = Gate::Token(&access);
718 for tool in TOOLS {
719 for action in tool.visible(&gate) {
720 assert!(reads_only(action.op), "{}.{}", tool.name, action.name);
721 }
722 }
723 let tools = listed(&gate);
724 for tool in &tools {
725 assert_eq!(tool["annotations"]["readOnlyHint"], true, "{}", tool["name"]);
726 assert_eq!(tool["annotations"]["destructiveHint"], false);
727 }
728 let issue = tools.iter().find(|tool| tool["name"] == "issue").unwrap();
729 assert_eq!(issue["inputSchema"]["properties"]["action"]["enum"], json!(["list", "get", "labels"]));
730 // Nothing of the agent tool is a read.
731 assert!(!tools.iter().any(|tool| tool["name"] == "agent"));
732 }
733
734 #[test]
735 fn a_narrow_token_sees_only_its_tools() {
736 let access = token(Some(vec![Scope::IssuesWrite]));
737 let names: Vec<Value> = listed(&Gate::Token(&access)).into_iter().map(|tool| tool["name"].clone()).collect();
738 // Labels and milestones are the repository's, managed with issues:write.
739 assert_eq!(names, vec![json!("repository"), json!("issue"), json!("plan"), json!("account")]);
740 // Notifications are a resource of their own: reading them lists
741 // only what reads.
742 let reader = token(Some(vec![Scope::NotificationsRead]));
743 let tools = listed(&Gate::Token(&reader));
744 let notifications = tools.iter().find(|tool| tool["name"] == "notifications").unwrap();
745 assert_eq!(
746 notifications["inputSchema"]["properties"]["action"]["enum"],
747 json!(["list", "get", "subscription", "watching", "watched"])
748 );
749 assert_eq!(notifications["annotations"]["readOnlyHint"], true);
750 let full = token(None);
751 assert_eq!(listed(&Gate::Token(&full)).len(), TOOLS.len());
752 assert_eq!(listed(&Gate::Everything).len(), TOOLS.len());
753 }
754
755 #[test]
756 fn a_tool_that_can_destroy_says_so() {
757 let tools = listed(&Gate::Everything);
758 let repository = tools.iter().find(|tool| tool["name"] == "repository").unwrap();
759 assert_eq!(repository["annotations"]["destructiveHint"], true);
760 assert_eq!(repository["annotations"]["readOnlyHint"], false);
761 let memory = tools.iter().find(|tool| tool["name"] == "memory").unwrap();
762 assert_eq!(memory["annotations"]["destructiveHint"], false);
763 }
764
765 #[test]
766 fn calls_resolve_to_their_operation_or_say_what_is_missing() {
767 let issue = Tool::by_name("issue").unwrap();
768 assert_eq!(resolve(issue, &json!({ "action": "get", "repo": "a/b", "number": 1 })), Ok(Op::GetIssue));
769 assert_eq!(resolve(issue, &json!({ "action": "get", "repo": "a/b" })), Err("issue.get needs number.".to_owned()));
770 assert!(resolve(issue, &json!({})).unwrap_err().starts_with("Give an action"));
771 assert!(resolve(issue, &json!({ "action": "explode" })).unwrap_err().contains("no action explode"));
772 let search = Tool::by_name("search").unwrap();
773 assert_eq!(resolve(search, &json!({ "query": "x" })), Ok(Op::Search));
774 let account = Tool::by_name("account").unwrap();
775 assert_eq!(resolve(account, &json!({})), Ok(Op::Whoami));
776 }
777
778 #[test]
779 fn teams_are_one_tool_and_a_workspace_reader_sees_only_its_reads() {
780 let team = Tool::by_name("team").unwrap();
781 let names: Vec<&str> = team.actions.iter().map(|action| action.name).collect();
782 assert_eq!(
783 names,
784 [
785 "list",
786 "get",
787 "create",
788 "update",
789 "delete",
790 "list_members",
791 "set_member",
792 "remove_member",
793 "list_child_teams",
794 "list_repos",
795 "set_repo",
796 "remove_repo",
797 "set_review_assignment",
798 "list_user_teams",
799 ]
800 );
801 let reader = token(Some(vec![Scope::WorkspaceRead]));
802 let tools = listed(&Gate::Token(&reader));
803 let listed_team = tools.iter().find(|tool| tool["name"] == "team").unwrap();
804 assert_eq!(
805 listed_team["inputSchema"]["properties"]["action"]["enum"],
806 json!(["list", "get", "list_members", "list_child_teams", "list_repos", "list_user_teams"])
807 );
808 assert_eq!(listed_team["annotations"]["readOnlyHint"], true);
809 // A team's role on a repository is who has access.
810 let admin = token(Some(vec![Scope::WorkspaceAdmin]));
811 let tools = listed(&Gate::Token(&admin));
812 let listed_team = tools.iter().find(|tool| tool["name"] == "team").unwrap();
813 let actions = listed_team["inputSchema"]["properties"]["action"]["enum"].as_array().unwrap();
814 assert!(actions.contains(&json!("set_review_assignment")) && !actions.contains(&json!("set_repo")));
815 let access = token(Some(vec![Scope::AccessAdmin]));
816 let tools = listed(&Gate::Token(&access));
817 let listed_team = tools.iter().find(|tool| tool["name"] == "team").unwrap();
818 assert_eq!(listed_team["inputSchema"]["properties"]["action"]["enum"], json!(["set_repo", "remove_repo"]));
819 // Both kinds of role a schema names are offered.
820 let roles = &listed(&Gate::Everything).into_iter().find(|tool| tool["name"] == "team").unwrap()["inputSchema"]
821 ["properties"]["role"]["enum"];
822 for role in ["member", "maintainer", "read", "admin"] {
823 assert!(roles.as_array().unwrap().contains(&json!(role)), "{role}");
824 }
825 assert_eq!(
826 resolve(team, &json!({ "action": "set_repo", "workspace": "acme", "team": "backend", "repo": "rocket" })),
827 Err("team.set_repo needs role.".to_owned())
828 );
829 }
830
831 #[test]
832 fn reviewers_and_code_owners_are_actions_of_their_tools() {
833 let pull = Tool::by_name("pull_request").unwrap();
834 assert_eq!(
835 resolve(pull, &json!({ "action": "request_reviewers", "repo": "a/b", "number": 1, "team_reviewers": ["backend"] })),
836 Ok(Op::RequestReviewers)
837 );
838 assert_eq!(pull.action("remove_requested_reviewers").map(|action| action.op), Some(Op::RemoveRequestedReviewers));
839 let repository = Tool::by_name("repository").unwrap();
840 assert_eq!(resolve(repository, &json!({ "action": "codeowners", "repo": "a/b" })), Ok(Op::GetCodeownersErrors));
841 assert!(reads_only(Op::GetCodeownersErrors));
842 assert!(!reads_only(Op::RequestReviewers));
843 }
844
845 /// How much smaller `tools/list` is than one tool per operation. Run
846 /// with `--nocapture` to see the numbers.
847 #[test]
848 fn the_tool_list_is_much_smaller_than_one_tool_per_operation() {
849 let before: Vec<Value> = Op::ALL
850 .into_iter()
851 .map(|op| json!({ "name": op.name(), "description": op.description(), "inputSchema": op.input() }))
852 .collect();
853 let after = listed(&Gate::Everything);
854 let before_bytes = serde_json::to_string(&json!({ "tools": before })).unwrap().len();
855 let after_bytes = serde_json::to_string(&json!({ "tools": after })).unwrap().len();
856 let agent = token(Preset::Agent.scopes());
857 let agent_bytes = serde_json::to_string(&json!({ "tools": listed(&Gate::Token(&agent)) })).unwrap().len();
858 let read = token(Preset::ReadOnly.scopes());
859 let read_bytes = serde_json::to_string(&json!({ "tools": listed(&Gate::Token(&read)) })).unwrap().len();
860 println!(
861 "tools/list: before {} tools, {before_bytes} bytes (~{} tokens); after {} tools, {after_bytes} bytes (~{} tokens); agent preset {agent_bytes} bytes (~{} tokens); read only {read_bytes} bytes (~{} tokens)",
862 before.len(),
863 before_bytes / 4,
864 after.len(),
865 after_bytes / 4,
866 agent_bytes / 4,
867 read_bytes / 4,
868 );
869 assert!(after_bytes * 2 < before_bytes, "{after_bytes} vs {before_bytes}");
870 }
871}