flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/api/src/mcp.rs

174 lines7,732 bytesCodeBlame
1//! MCP over streamable HTTP. The server keeps no session state, so every
2//! POST is answered directly with JSON.
3
4use g1t_contracts::{Outcome, Viewer};
5use serde_json::{Value, json};
6use worker::{Method, Request, Response, Result};
7
8use crate::oauth::MCP_CHALLENGE;
9use crate::operations::{Op, Services};
10
11const SUPPORTED_VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];
12
13const INSTRUCTIONS: &str = "g1t is a git forge with issues and pull requests, built so that many agents can work on the same issue at once.
14To work on an issue: get_issue to read it and see the pull requests already made for it, then create_pull_request with the issue's number. You get a draft pull request with its own fork to clone and push to. Call record_session as you work so people can see your reasoning, push your commits, and call mark_pull_request_ready with a summary.
15Before going far, read `overlaps` on get_pull_request: other pull requests in progress that change the same files. One for a different issue will conflict with yours, so narrow your change or say so. `behind` means main has moved; pull it into your fork and push. Once your pull request is ready, the issue's acceptance checks are run for you in a clean sandbox; read their output from get_pull_request and push a fix if they fail.
16Before you start, recall what the project and its workspace remember; when you learn something the next agent would need, remember it (scope project for this codebase, workspace for what holds across projects). Never a secret.
17Issues and pull requests are named by repository (\"owner/name\") and number, and share one sequence of numbers.";
18
19fn result(id: &Value, value: Value) -> Value {
20 json!({ "jsonrpc": "2.0", "id": id, "result": value })
21}
22
23fn error(id: &Value, code: i32, message: &str) -> Value {
24 json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
25}
26
27/// Answers one JSON-RPC request, or `None` for a notification.
28async fn answer(services: &Services, viewer: &Viewer, request: &Value) -> Result<Option<Value>> {
29 // Notifications carry no id and get no response.
30 let Some(id) = request.get("id") else {
31 return Ok(None);
32 };
33 let params = &request["params"];
34 let answer = match request["method"].as_str().unwrap_or_default() {
35 "initialize" => {
36 let requested = params["protocolVersion"].as_str().unwrap_or_default();
37 let version = SUPPORTED_VERSIONS
38 .into_iter()
39 .find(|version| *version == requested)
40 .unwrap_or(SUPPORTED_VERSIONS[0]);
41 result(
42 id,
43 json!({
44 "protocolVersion": version,
45 "capabilities": { "tools": {} },
46 "serverInfo": { "name": "g1t", "version": "0.1.0" },
47 "instructions": INSTRUCTIONS,
48 }),
49 )
50 }
51 "ping" => result(id, json!({})),
52 "tools/list" => {
53 // An agent sees only the tools its token may use.
54 let tools: Vec<Value> = Op::ALL
55 .into_iter()
56 .filter(|op| services.scope.as_ref().is_none_or(|scope| op.allowed_by(scope)))
57 .map(|op| {
58 json!({
59 "name": op.name(),
60 "description": op.description(),
61 "inputSchema": op.input(),
62 })
63 })
64 .collect();
65 result(id, json!({ "tools": tools }))
66 }
67 "tools/call" => {
68 let Some(op) = Op::by_name(params["name"].as_str().unwrap_or_default()) else {
69 return Ok(Some(error(id, -32602, "Unknown tool.")));
70 };
71 let outcome = crate::audit::run(op, services, viewer, &params["arguments"]).await?;
72 // A failed operation is a tool result the model can read and
73 // act on, not a protocol error.
74 let (text, failed) = match outcome {
75 // In `snake_case`, as the REST API answers; the protocol's
76 // own envelope keeps MCP's spelling.
77 Outcome::Ok(value) => (
78 serde_json::to_string_pretty(&g1t_kit::wire::snake_case(value))?,
79 false,
80 ),
81 Outcome::Fail(failure) => (failure.message, true),
82 };
83 result(
84 id,
85 json!({ "content": [{ "type": "text", "text": text }], "isError": failed }),
86 )
87 }
88 method => error(id, -32601, &format!("Method not found: {method}")),
89 };
90 Ok(Some(answer))
91}
92
93/// What someone sees when they open the server's address in a browser:
94/// what this is, how to connect, and what it offers.
95fn card() -> Value {
96 let tools: Vec<Value> = Op::ALL
97 .into_iter()
98 .map(|op| json!({ "name": op.name(), "description": op.description() }))
99 .collect();
100 json!({
101 "name": "g1t",
102 "description": "The g1t MCP server: issues, pull requests and sessions for agents.",
103 "endpoint": "https://mcp.g1t.sh",
104 "transport": "streamable-http",
105 "protocol_versions": SUPPORTED_VERSIONS,
106 "connect": "claude mcp add --transport http g1t https://mcp.g1t.sh",
107 "authorization": {
108 "required": true,
109 "oauth_protected_resource": "https://mcp.g1t.sh/.well-known/oauth-protected-resource",
110 "alternative": "Authorization: Bearer <g1t access token>",
111 },
112 "documentation_url": "https://docs.g1t.sh/guides/bring-your-own-agent/",
113 "instructions": INSTRUCTIONS,
114 "tools": tools,
115 })
116}
117
118pub async fn handle(
119 mut request: Request,
120 services: &Services,
121 viewer: &Viewer,
122) -> Result<Response> {
123 if request.method() != Method::Post {
124 // A client asking for a stream of server messages is told there is
125 // none. Anyone else, a person with a browser, gets a description.
126 let wants_stream = request
127 .headers()
128 .get("accept")?
129 .is_some_and(|accept| accept.contains("text/event-stream"));
130 if request.method() == Method::Get && !wants_stream {
131 return Response::from_json(&card());
132 }
133 let mut response = Response::empty()?.with_status(405);
134 response.headers_mut().set("allow", "GET, POST")?;
135 return Ok(response);
136 }
137 // Calls need a signed-in user. Answering 401 with this header is what
138 // makes a client open the browser to sign in.
139 if viewer.is_none() {
140 let mut response = Response::from_json(&error(
141 &Value::Null,
142 -32001,
143 "Sign in to use the g1t MCP server.",
144 ))?
145 .with_status(401);
146 response
147 .headers_mut()
148 .set("www-authenticate", MCP_CHALLENGE)?;
149 return Ok(response);
150 }
151 let Ok(body) = request.json::<Value>().await else {
152 return Ok(
153 Response::from_json(&error(&Value::Null, -32700, "Parse error"))?.with_status(400),
154 );
155 };
156 let accepted = || Ok(Response::empty()?.with_status(202));
157 match body {
158 Value::Array(batch) => {
159 let mut answers = Vec::new();
160 for request in &batch {
161 answers.extend(answer(services, viewer, request).await?);
162 }
163 if answers.is_empty() {
164 accepted()
165 } else {
166 Response::from_json(&answers)
167 }
168 }
169 single => match answer(services, viewer, &single).await? {
170 Some(answer) => Response::from_json(&answer),
171 None => accepted(),
172 },
173 }
174}