Skip to content

Commit 2570b16

Browse files
salman1993claude
andcommitted
fix(goose): bind the MCP token to one session, and fix review findings
goose saves each session's extensions, with the Buzz server's bearer token, in its sessions.db. The token now admits one MCP session: the agent's initialize gets a random Mcp-Session-Id, and every later request must send it, so a token read from disk admits nothing. A message before initialize (rmcp first asks server/discover) needs no session. - Enter in a provider's key field saves the key, not the agent settings. - Only a send, edit or react that succeeded suppresses goose's text; a read or a failed send still posts it. - A turn that ends while a steer into it is answered now settles. - The provider dialog returns focus to its trigger. - Settings refuses a workspace that is not absolute or ~/… Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Salman Mohammed <[email protected]>
1 parent 128b6ea commit 2570b16

8 files changed

Lines changed: 353 additions & 61 deletions

File tree

‎src-tauri/src/host_mcp.rs‎

Lines changed: 74 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,16 @@
88
//! per server authorizes every request as `Authorization: Bearer <token>`.
99
//! `Host` must name the bound address, and a request that sends `Origin`
1010
//! (a web page) is refused. Nothing is logged.
11+
//! - The token admits one MCP session. The agent's `initialize` is answered
12+
//! with a random `Mcp-Session-Id`, and every later request must send it. An
13+
//! agent may save its server's token to disk (goose does), so a token read
14+
//! from there is useless once the agent connected.
1115
//! - A refused request gets 404, never 401 or 403: MCP clients answer those
1216
//! by starting an OAuth sign-in.
13-
//! - It is stateless and answers in JSON, never SSE. `POST /mcp` carries one
14-
//! message: a request is answered with the page's reply, and a notification
15-
//! or response with 202. `GET` and `DELETE` get 405, since there is no
16-
//! server stream or session to end.
17+
//! - It answers in JSON, never SSE. `POST /mcp` carries one message: a request
18+
//! is answered with the page's reply, and a notification or response with
19+
//! 202. `GET` and `DELETE` get 405: there is no server stream, and the
20+
//! session ends with the server.
1721
//! - Each connection answers one request and closes. A client that closes
1822
//! before its answer drops the request; the page's late reply is refused.
1923
//! - A server belongs to the plugin and the page that started it. It stops
@@ -29,6 +33,7 @@ use serde::Serialize;
2933
use std::collections::HashMap;
3034
use std::convert::Infallible;
3135
use std::net::Ipv4Addr;
36+
use std::sync::atomic::{AtomicBool, Ordering};
3237
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
3338
use std::time::Duration;
3439
use tauri::ipc::Channel;
@@ -47,6 +52,7 @@ const BODY_LIMIT: usize = 4 * 1024 * 1024;
4752
const BODY_TIMEOUT: Duration = Duration::from_secs(30);
4853
const REPLY_LIMIT: usize = 16 * 1024 * 1024;
4954
const ENDPOINT: &str = "/mcp";
55+
const SESSION: HeaderName = HeaderName::from_static("mcp-session-id");
5056

5157
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
5258
#[serde(tag = "type", rename_all = "camelCase")]
@@ -71,6 +77,10 @@ pub(crate) struct McpServerInfo {
7177
struct Shared {
7278
authority: String,
7379
token: String,
80+
/// The `Mcp-Session-Id` of the one session the token admits.
81+
session: String,
82+
/// Whether an `initialize` claimed the session.
83+
claimed: AtomicBool,
7484
events: Channel<McpEvent>,
7585
stop: CancellationToken,
7686
pending: Mutex<Pending>,
@@ -137,12 +147,17 @@ impl HostMcpServers {
137147
let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(failed)?;
138148
listener.set_nonblocking(true).map_err(failed)?;
139149
let authority = listener.local_addr().map_err(failed)?.to_string();
140-
let mut secret = [0; 32];
141-
getrandom::fill(&mut secret).map_err(|_| "Could not start the MCP server")?;
142-
let token = URL_SAFE_NO_PAD.encode(secret);
150+
let secret = || {
151+
let mut secret = [0; 32];
152+
getrandom::fill(&mut secret).map_err(|_| "Could not start the MCP server")?;
153+
Ok::<_, &str>(URL_SAFE_NO_PAD.encode(secret))
154+
};
155+
let token = secret()?;
143156
let shared = Arc::new(Shared {
144157
authority: authority.clone(),
145158
token: token.clone(),
159+
session: secret()?,
160+
claimed: AtomicBool::new(false),
146161
events,
147162
stop: CancellationToken::new(),
148163
pending: Mutex::default(),
@@ -251,22 +266,31 @@ async fn answer(
251266
shared: &Shared,
252267
request: Request<Incoming>,
253268
) -> Result<Response<Full<Bytes>>, Infallible> {
254-
let (status, body) = match refuse(shared, &request) {
255-
Some(status) => (status, None),
256-
None => {
269+
let (status, body, joined) = match refuse(shared, &request) {
270+
Err(status) => (status, None, false),
271+
Ok(named) => {
257272
let body = Limited::new(request.into_body(), BODY_LIMIT).collect();
258273
match tokio::time::timeout(BODY_TIMEOUT, body).await {
259274
Ok(Ok(body)) => match String::from_utf8(body.to_bytes().into()) {
260-
Ok(body) => forward(shared, body).await,
261-
Err(_) => (StatusCode::BAD_REQUEST, None),
275+
Ok(body) => match join(shared, named, &body) {
276+
Ok(joined) => {
277+
let (status, reply) = forward(shared, body).await;
278+
(status, reply, joined)
279+
}
280+
Err(status) => (status, None, false),
281+
},
282+
Err(_) => (StatusCode::BAD_REQUEST, None, false),
262283
},
263-
_ => (StatusCode::BAD_REQUEST, None),
284+
_ => (StatusCode::BAD_REQUEST, None, false),
264285
}
265286
}
266287
};
267288
let mut response = Response::builder()
268289
.status(status)
269290
.header(header::CACHE_CONTROL, "no-store");
291+
if joined && (status == StatusCode::OK || status == StatusCode::ACCEPTED) {
292+
response = response.header(SESSION, &shared.session);
293+
}
270294
if status == StatusCode::OK {
271295
response = response.header(header::CONTENT_TYPE, "application/json");
272296
}
@@ -311,8 +335,9 @@ async fn forward(shared: &Shared, body: String) -> (StatusCode, Option<String>)
311335
}
312336
}
313337

314-
/// The status that refuses `request`, unless it is an authorized `POST /mcp`.
315-
fn refuse(shared: &Shared, request: &Request<Incoming>) -> Option<StatusCode> {
338+
/// Whether an authorized `POST /mcp` names the session, or the status that
339+
/// refuses `request`.
340+
fn refuse(shared: &Shared, request: &Request<Incoming>) -> Result<bool, StatusCode> {
316341
let token = header(request, header::AUTHORIZATION)
317342
.and_then(|value| value.strip_prefix("Bearer "))
318343
.unwrap_or_default();
@@ -322,23 +347,52 @@ fn refuse(shared: &Shared, request: &Request<Incoming>) -> Option<StatusCode> {
322347
|| request.uri().path() != ENDPOINT
323348
|| !same(token.as_bytes(), shared.token.as_bytes())
324349
{
325-
return Some(StatusCode::NOT_FOUND);
350+
return Err(StatusCode::NOT_FOUND);
326351
}
327352
// No server stream for `GET` and no session for `DELETE` to end.
328353
if request.method() != Method::POST {
329-
return Some(StatusCode::METHOD_NOT_ALLOWED);
354+
return Err(StatusCode::METHOD_NOT_ALLOWED);
330355
}
331356
let json = header(request, header::CONTENT_TYPE)
332357
.and_then(|value| value.split(';').next())
333358
.is_some_and(|kind| kind.trim().eq_ignore_ascii_case("application/json"));
334359
if !json {
335-
return Some(StatusCode::UNSUPPORTED_MEDIA_TYPE);
360+
return Err(StatusCode::UNSUPPORTED_MEDIA_TYPE);
336361
}
337362
let length = header(request, header::CONTENT_LENGTH).and_then(|value| value.parse().ok());
338363
if length.is_some_and(|length: usize| length > BODY_LIMIT) {
339-
return Some(StatusCode::PAYLOAD_TOO_LARGE);
364+
return Err(StatusCode::PAYLOAD_TOO_LARGE);
365+
}
366+
match header(request, SESSION) {
367+
Some(session) if same(session.as_bytes(), shared.session.as_bytes()) => Ok(true),
368+
Some(_) => Err(StatusCode::NOT_FOUND),
369+
None => Ok(false),
370+
}
371+
}
372+
373+
/// Whether `body` is in the session: it named it, or it is the `initialize`
374+
/// that claims it. Until then a message may come without one, as a client's
375+
/// `server/discover` does; after it, the token alone admits nothing.
376+
fn join(shared: &Shared, named: bool, body: &str) -> Result<bool, StatusCode> {
377+
#[derive(serde::Deserialize)]
378+
struct Message {
379+
method: Option<String>,
380+
}
381+
if named {
382+
return Ok(true);
383+
}
384+
let initialize = serde_json::from_str::<Message>(body)
385+
.is_ok_and(|message| message.method.as_deref() == Some("initialize"));
386+
let claimed = if initialize {
387+
shared.claimed.swap(true, Ordering::SeqCst)
388+
} else {
389+
shared.claimed.load(Ordering::SeqCst)
390+
};
391+
if claimed {
392+
Err(StatusCode::NOT_FOUND)
393+
} else {
394+
Ok(initialize)
340395
}
341-
None
342396
}
343397

344398
fn header(request: &Request<Incoming>, name: HeaderName) -> Option<&str> {

‎src-tauri/src/host_mcp/tests.rs‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,94 @@ async fn accepts_a_notification_without_a_body() {
133133
assert_eq!(status(&client.await.unwrap()), "202");
134134
}
135135

136+
/// The `Mcp-Session-Id` a response names.
137+
fn session(response: &str) -> Option<&str> {
138+
response
139+
.split("\r\n")
140+
.find_map(|line| line.strip_prefix("mcp-session-id: "))
141+
}
142+
143+
/// Sends `request` and answers the message it carries with `reply`.
144+
async fn exchange(
145+
servers: &HostMcpServers,
146+
info: &McpServerInfo,
147+
events: &mut mpsc::UnboundedReceiver<serde_json::Value>,
148+
request: String,
149+
reply: Option<&str>,
150+
) -> String {
151+
let client = tokio::spawn({
152+
let info = info.clone();
153+
async move { send(&info, request).await }
154+
});
155+
let event = next(events).await;
156+
servers
157+
.reply(
158+
"plugin",
159+
info.handle,
160+
event["request"].as_u64().unwrap(),
161+
reply.map(Into::into),
162+
)
163+
.unwrap();
164+
client.await.unwrap()
165+
}
166+
167+
#[tokio::test]
168+
async fn admits_only_the_session_that_initialized() {
169+
let servers = HostMcpServers::default();
170+
let (channel, mut events) = channel();
171+
let info = servers
172+
.serve(servers.page(), "plugin".into(), channel)
173+
.unwrap();
174+
// Before `initialize`, a message needs no session, and joins none.
175+
let discover = r#"{"jsonrpc":"2.0","id":0,"method":"server/discover"}"#;
176+
let not_found = r#"{"jsonrpc":"2.0","id":0,"error":{"code":-32601,"message":"No"}}"#;
177+
let response = exchange(
178+
&servers,
179+
&info,
180+
&mut events,
181+
post(&info, &info.token, "", discover),
182+
Some(not_found),
183+
)
184+
.await;
185+
assert_eq!(status(&response), "200");
186+
assert_eq!(session(&response), None);
187+
let initialize = r#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#;
188+
let initialized = r#"{"jsonrpc":"2.0","id":1,"result":{}}"#;
189+
let response = exchange(
190+
&servers,
191+
&info,
192+
&mut events,
193+
post(&info, &info.token, "", initialize),
194+
Some(initialized),
195+
)
196+
.await;
197+
assert_eq!(status(&response), "200");
198+
let id = session(&response).expect("a session id").to_owned();
199+
// The token alone, as read from where the agent saved it, admits nothing
200+
// more: not another `initialize`, nor a guessed session.
201+
let ping = r#"{"jsonrpc":"2.0","id":2,"method":"ping"}"#;
202+
for (extra, body) in [
203+
("", ping),
204+
("", initialize),
205+
("Mcp-Session-Id: guess\r\n", ping),
206+
] {
207+
let request = post(&info, &info.token, extra, body);
208+
assert_eq!(status(&send(&info, request).await), "404");
209+
}
210+
assert!(events.try_recv().is_err());
211+
let named = format!("Mcp-Session-Id: {id}\r\n");
212+
let response = exchange(
213+
&servers,
214+
&info,
215+
&mut events,
216+
post(&info, &info.token, &named, ping),
217+
None,
218+
)
219+
.await;
220+
assert_eq!(status(&response), "202");
221+
assert_eq!(session(&response), Some(id.as_str()));
222+
}
223+
136224
#[tokio::test]
137225
async fn refuses_without_starting_oauth() {
138226
let servers = HostMcpServers::default();

‎src/bundled/goose/goose-testing.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ export type FakeGoose = {
4343
env: Readonly<Record<string, string | null>>;
4444
/** When set, a turn stays open until it is finished. */
4545
hold: boolean;
46+
/** When set, a turn takes a steer and ends before goose answers the steer. */
47+
endOnSteer: boolean;
4648
killed: boolean;
4749
/** Asks the client a request and resolves with its response. */
4850
ask(method: string, params: Record<string, unknown>): Promise<Message>;
@@ -170,6 +172,7 @@ export function fakeSpawn(
170172
deleted: [],
171173
env: process.env ?? {},
172174
hold: options.hold ?? false,
175+
endOnSteer: false,
173176
killed: false,
174177
ask: (method, params) => {
175178
const requestId = `goose-${++requests}`;
@@ -281,6 +284,7 @@ export function fakeSpawn(
281284
.map((block) => block.text)
282285
.join(""),
283286
);
287+
if (fake.endOnSteer) turn.finish();
284288
return reply(id, { runId: turn.runId, messageId: "m" });
285289
}
286290
case "session/cancel":

‎src/bundled/goose/goose.live.test.ts‎

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,17 +65,31 @@ const spawn: Spawn = async (_id, options: HostProcessOptions = {}) => {
6565
/** The HTTP requests the MCP servers received, by method and status. */
6666
const hits: { method: string; status: number }[] = [];
6767

68+
const method = (body: string): unknown => {
69+
try {
70+
return (JSON.parse(body) as { method?: unknown } | null)?.method;
71+
} catch {
72+
return undefined;
73+
}
74+
};
75+
6876
/** What the app's native listener does: a token per server, 404 for a wrong
69-
* one, 405 for `GET`, and a JSON reply or 202 for each `POST /mcp`. */
77+
* one, 405 for `GET`, and a JSON reply or 202 for each `POST /mcp`. The
78+
* `initialize` claims the server's one session; later requests must name it. */
7079
const serve: ServeMcp = async (handler) => {
7180
const token = randomBytes(32).toString("base64url");
81+
const session = randomBytes(32).toString("base64url");
82+
let claimed = false;
7283
const server = createServer((request, response) => {
84+
let joined = false;
7385
const end = (status: number, body?: string) => {
7486
hits.push({ method: request.method ?? "", status });
75-
response.writeHead(
76-
status,
77-
body ? { "Content-Type": "application/json" } : {},
78-
);
87+
response.writeHead(status, {
88+
...(joined && (status === 200 || status === 202)
89+
? { "Mcp-Session-Id": session }
90+
: {}),
91+
...(body ? { "Content-Type": "application/json" } : {}),
92+
});
7993
response.end(body);
8094
};
8195
if (
@@ -84,9 +98,17 @@ const serve: ServeMcp = async (handler) => {
8498
)
8599
return end(404);
86100
if (request.method !== "POST") return end(405);
101+
const named = request.headers["mcp-session-id"];
102+
if (named !== undefined && named !== session) return end(404);
87103
let body = "";
88104
request.setEncoding("utf8").on("data", (data) => (body += data));
89105
request.on("end", async () => {
106+
if (named === undefined) {
107+
// Before it, a message needs no session (goose first asks
108+
// `server/discover`).
109+
if (claimed) return end(404);
110+
if (method(body) === "initialize") claimed = joined = true;
111+
} else joined = true;
90112
const reply = await answerMcp(handler, body);
91113
end(reply === undefined ? 202 : 200, JSON.stringify(reply));
92114
});
@@ -190,6 +212,20 @@ describe.skipIf(!BIN)("goose-acp", () => {
190212
// refused.
191213
expect(hits.some((hit) => hit.status === 200)).toBe(true);
192214
expect(hits.filter((hit) => hit.status === 404)).toEqual([]);
215+
// goose saves the token with the session; alone, it admits nothing.
216+
const server = session.server;
217+
if (!server) throw new Error("no Buzz MCP server");
218+
const stolen = await fetch(server.url, {
219+
method: "POST",
220+
headers: {
221+
...Object.fromEntries(
222+
server.headers.map(({ name, value }) => [name, value]),
223+
),
224+
"Content-Type": "application/json",
225+
},
226+
body: '{"jsonrpc":"2.0","id":1,"method":"tools/list"}',
227+
});
228+
expect(stolen.status).toBe(404);
193229
expect(
194230
calls.find((call) => call.method === "tools/call")?.conversation,
195231
).toBe("channel/root");

0 commit comments

Comments
 (0)