Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 60 additions & 17 deletions src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,18 @@ use uuid::Uuid;
use crate::api::{Http, McpHttpError};
use crate::credentials::Credential;

const FRAME_LIMIT: usize = 8192;
/// The largest input line the bridge accepts. The server's tool schemas allow
/// strings of up to 65,536 characters (`review_rule.create`'s `ast_rule`), and
/// JSON can spell each one as a six-byte `\uXXXX` escape, so 1 MiB holds any
/// call they accept with room for the envelope.
const FRAME_LIMIT: usize = 1024 * 1024;
const PROTOCOL: &str = "2025-11-25";

#[derive(Debug, thiserror::Error)]
pub(crate) enum McpError {
#[error(transparent)]
Http(#[from] McpHttpError),
#[error("MCP input exceeds 8192 bytes")]
#[error("MCP input exceeds {FRAME_LIMIT} bytes")]
TooLarge,
#[error("MCP input is not UTF-8")]
Utf8,
Expand Down Expand Up @@ -245,7 +249,8 @@ impl Session {
}

async fn read_frame(input: &mut BufReader<Stdin>) -> Result<Option<Vec<u8>>, McpError> {
let mut frame = Vec::with_capacity(FRAME_LIMIT);
// Grown as the line arrives: most frames are far below the limit.
let mut frame = Vec::new();
loop {
let available = input.fill_buf().await.map_err(|_| McpError::Input)?;
if available.is_empty() {
Expand Down Expand Up @@ -324,7 +329,7 @@ async fn write(output: &mut Stdout, response: &Value) -> Result<(), McpError> {
}

pub(crate) async fn run(http: &Http, token: &SecretString) -> Result<(), McpError> {
let mut input = BufReader::with_capacity(FRAME_LIMIT, tokio::io::stdin());
let mut input = BufReader::new(tokio::io::stdin());
let mut output = tokio::io::stdout();
let mut session = Session::New;
loop {
Expand Down Expand Up @@ -456,19 +461,12 @@ mod tests {
origin::Origin,
};

#[tokio::test]
async fn native_call_preserves_a_resolved_device_credential_target() {
let organization_id = Uuid::parse_str("0190f3a0-0000-7000-8000-000000000001").unwrap();
// The credential loader returns this stored organization when no --org
// is supplied. Native calls must target it just as environment calls do.
let credential = Credential {
token: SecretString::from("pld_device_fixture"),
organization_id,
scope: Some("reviews:read knowledge:read".to_owned()),
expires_at: None,
source: Source::Keychain,
};
let seen = Arc::new(Mutex::new(Vec::new()));
type Seen = Arc<Mutex<Vec<Value>>>;

/// A stand-in MCP server that completes the handshake and records the
/// params of each `tools/call`.
async fn serve_tools() -> (Origin, Seen, tokio::task::JoinHandle<()>) {
let seen = Seen::default();
let observed = Arc::clone(&seen);
let app = Router::new().route(
"/mcp",
Expand All @@ -492,6 +490,51 @@ mod tests {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = Origin::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
(origin, seen, server)
}

/// `proofline ask` sends its question through the same bounded transport.
/// A full-length `ask_codebase` question in a CJK script is about 12 KB.
#[tokio::test]
async fn a_native_call_carries_a_full_length_question_in_a_cjk_script() {
let organization_id = Uuid::parse_str("0190f3a0-0000-7000-8000-000000000001").unwrap();
let credential = Credential {
token: SecretString::from("pld_device_fixture"),
organization_id,
scope: Some("knowledge:read".to_owned()),
expires_at: None,
source: Source::Keychain,
};
let (origin, seen, server) = serve_tools().await;
let question = "代".repeat(4000);
call(
&Http::new(origin).unwrap(),
&credential,
"ask_codebase",
json!({"repository":"owner/name","question":question}),
)
.await
.unwrap();
assert_eq!(
seen.lock().unwrap()[0]["arguments"]["question"],
json!(question)
);
server.abort();
}

#[tokio::test]
async fn native_call_preserves_a_resolved_device_credential_target() {
let organization_id = Uuid::parse_str("0190f3a0-0000-7000-8000-000000000001").unwrap();
// The credential loader returns this stored organization when no --org
// is supplied. Native calls must target it just as environment calls do.
let credential = Credential {
token: SecretString::from("pld_device_fixture"),
organization_id,
scope: Some("reviews:read knowledge:read".to_owned()),
expires_at: None,
source: Source::Keychain,
};
let (origin, seen, server) = serve_tools().await;
let result = call(
&Http::new(origin).unwrap(),
&credential,
Expand Down
6 changes: 3 additions & 3 deletions tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3439,12 +3439,12 @@ async fn config_input_and_credential_failures_make_no_tool_call() {
assert!(String::from_utf8_lossy(&output.stderr).contains("NAME=VALUE"));
assert_eq!(server.frames.load(Ordering::SeqCst), 0);

let oversized =
json!({"operation":"repository.wiki_settings.update", "input":{"text":"x".repeat(8192)}});
let oversized = json!({"operation":"repository.wiki_settings.update",
"input":{"text":"x".repeat(1024 * 1024)}});
std::fs::write(&file, serde_json::to_vec(&oversized).unwrap()).unwrap();
let output = cli(&server.origin, &["config", "propose", path]).await;
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("MCP input exceeds 8192 bytes"));
assert!(String::from_utf8_lossy(&output.stderr).contains("MCP input exceeds 1048576 bytes"));
assert!(server.requests().is_empty());
// The existing transport negotiates before checking the tool-call frame.
assert_eq!(server.frames.load(Ordering::SeqCst), 2);
Expand Down
34 changes: 33 additions & 1 deletion tests/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const ORG: &str = "0190f3a0-0000-7000-8000-000000000001";
const OTHER_ORG: &str = "0190f3a0-0000-7000-8000-000000000002";
const TOKEN: &str = "pld_CLI_MCP_SYNTHETIC_TOKEN_CANARY";
const PROTOCOL: &str = "2025-11-25";
const FRAME_LIMIT: usize = 8192;
const FRAME_LIMIT: usize = 1024 * 1024;
const BODY_LIMIT: usize = 8 * 1024 * 1024;
const WAIT: Duration = Duration::from_secs(10);
const REFUSAL_CANARY: &str = "RAW_REFUSAL_BODY_CANARY";
Expand Down Expand Up @@ -624,6 +624,38 @@ async fn the_bridge_needs_no_organization_and_relays_each_calls_target() {
assert_eq!(fixture.finish().await.len(), 3);
}

/// The server's `ask_codebase` takes a question of up to 4,000 characters, and
/// in a CJK script that is about 12 KB on the wire. The bridge relays it under
/// its own id, and the session carries on.
#[tokio::test]
async fn a_full_length_question_in_a_cjk_script_is_relayed_and_the_session_continues() {
let mut fixture = Fixture::start().await;
let mut bridge = Bridge::start(&fixture.origin, ORG);
negotiate(&mut bridge, &mut fixture, false).await;
let call = json!({"jsonrpc":"2.0","id":30,"method":"tools/call","params":{
"name":"ask_codebase",
"arguments":{"repository":"owner/name","question":"代".repeat(4000)}
}});
assert!(serde_json::to_vec(&call).unwrap().len() > 12_000);
exchange_value(
&mut bridge,
&mut fixture,
call,
result(json!(30), json!({"isError":false,"content":[]})),
)
.await;
exchange_value(
&mut bridge,
&mut fixture,
request(json!(31), "ping"),
result(json!(31), json!({})),
)
.await;
let finished = bridge.finish(true).await;
assert!(finished.status.success(), "{:?}", finished.diagnostic);
assert_eq!(fixture.finish().await.len(), 4);
}

#[tokio::test]
async fn negotiated_stdio_forwards_exact_messages_headers_and_machine_status_without_notification_output()
{
Expand Down