pr_01m47d24b0e6n91zwymwxg0vpx/apps/api/src/mcp.rs

168 lines7,274 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.
16Issues and pull requests are named by repository (\"owner/name\") and number, and share one sequence of numbers.";
17
18fn result(id: &Value, value: Value) -> Value {
19 json!({ "jsonrpc": "2.0", "id": id, "result": value })
20}
21
22fn error(id: &Value, code: i32, message: &str) -> Value {
23 json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
24}
25
26/// Answers one JSON-RPC request, or `None` for a notification.
27async fn answer(services: &Services, viewer: &Viewer, request: &Value) -> Result<Option<Value>> {
28 // Notifications carry no id and get no response.
29 let Some(id) = request.get("id") else {
30 return Ok(None);
31 };
32 let params = &request["params"];
33 let answer = match request["method"].as_str().unwrap_or_default() {
34 "initialize" => {
35 let requested = params["protocolVersion"].as_str().unwrap_or_default();
36 let version = SUPPORTED_VERSIONS
37 .into_iter()
38 .find(|version| *version == requested)
39 .unwrap_or(SUPPORTED_VERSIONS[0]);
40 result(
41 id,
42 json!({
43 "protocolVersion": version,
44 "capabilities": { "tools": {} },
45 "serverInfo": { "name": "g1t", "version": "0.1.0" },
46 "instructions": INSTRUCTIONS,
47 }),
48 )
49 }
50 "ping" => result(id, json!({})),
51 "tools/list" => {
52 // An agent sees only the tools its token may use.
53 let tools: Vec<Value> = Op::ALL
54 .into_iter()
55 .filter(|op| services.scope.as_ref().is_none_or(|scope| op.allowed_by(scope)))
56 .map(|op| {
57 json!({
58 "name": op.name(),
59 "description": op.description(),
60 "inputSchema": op.input(),
61 })
62 })
63 .collect();
64 result(id, json!({ "tools": tools }))
65 }
66 "tools/call" => {
67 let Some(op) = Op::by_name(params["name"].as_str().unwrap_or_default()) else {
68 return Ok(Some(error(id, -32602, "Unknown tool.")));
69 };
70 let outcome = op.run(services, viewer, &params["arguments"]).await?;
71 // A failed operation is a tool result the model can read and
72 // act on, not a protocol error.
73 let (text, failed) = match outcome {
74 Outcome::Ok(value) => (serde_json::to_string_pretty(&value)?, false),
75 Outcome::Fail(failure) => (failure.message, true),
76 };
77 result(
78 id,
79 json!({ "content": [{ "type": "text", "text": text }], "isError": failed }),
80 )
81 }
82 method => error(id, -32601, &format!("Method not found: {method}")),
83 };
84 Ok(Some(answer))
85}
86
87/// What someone sees when they open the server's address in a browser:
88/// what this is, how to connect, and what it offers.
89fn card() -> Value {
90 let tools: Vec<Value> = Op::ALL
91 .into_iter()
92 .map(|op| json!({ "name": op.name(), "description": op.description() }))
93 .collect();
94 json!({
95 "name": "g1t",
96 "description": "The g1t MCP server: issues, pull requests and sessions for agents.",
97 "endpoint": "https://mcp.g1t.sh",
98 "transport": "streamable-http",
99 "protocol_versions": SUPPORTED_VERSIONS,
100 "connect": "claude mcp add --transport http g1t https://mcp.g1t.sh",
101 "authorization": {
102 "required": true,
103 "oauth_protected_resource": "https://mcp.g1t.sh/.well-known/oauth-protected-resource",
104 "alternative": "Authorization: Bearer <g1t access token>",
105 },
106 "documentation_url": "https://docs.g1t.sh/guides/bring-your-own-agent/",
107 "instructions": INSTRUCTIONS,
108 "tools": tools,
109 })
110}
111
112pub async fn handle(
113 mut request: Request,
114 services: &Services,
115 viewer: &Viewer,
116) -> Result<Response> {
117 if request.method() != Method::Post {
118 // A client asking for a stream of server messages is told there is
119 // none. Anyone else, a person with a browser, gets a description.
120 let wants_stream = request
121 .headers()
122 .get("accept")?
123 .is_some_and(|accept| accept.contains("text/event-stream"));
124 if request.method() == Method::Get && !wants_stream {
125 return Response::from_json(&card());
126 }
127 let mut response = Response::empty()?.with_status(405);
128 response.headers_mut().set("allow", "GET, POST")?;
129 return Ok(response);
130 }
131 // Calls need a signed-in user. Answering 401 with this header is what
132 // makes a client open the browser to sign in.
133 if viewer.is_none() {
134 let mut response = Response::from_json(&error(
135 &Value::Null,
136 -32001,
137 "Sign in to use the g1t MCP server.",
138 ))?
139 .with_status(401);
140 response
141 .headers_mut()
142 .set("www-authenticate", MCP_CHALLENGE)?;
143 return Ok(response);
144 }
145 let Ok(body) = request.json::<Value>().await else {
146 return Ok(
147 Response::from_json(&error(&Value::Null, -32700, "Parse error"))?.with_status(400),
148 );
149 };
150 let accepted = || Ok(Response::empty()?.with_status(202));
151 match body {
152 Value::Array(batch) => {
153 let mut answers = Vec::new();
154 for request in &batch {
155 answers.extend(answer(services, viewer, request).await?);
156 }
157 if answers.is_empty() {
158 accepted()
159 } else {
160 Response::from_json(&answers)
161 }
162 }
163 single => match answer(services, viewer, &single).await? {
164 Some(answer) => Response::from_json(&answer),
165 None => accepted(),
166 },
167 }
168}