mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 01:05:10 +08:00
fix: adjust secondary button height and enhance MultiCombobox input behavior
This commit is contained in:
1 parent
fe17e15e75
commit
89631bdab0
22 files changed
+754
-84
No files matched your search
@@ -459,6 +459,7 @@ pub fn dynamic_mcp(
|
||||
Error::Protocol(format!("MCP tool {} is missing input schema", wire.name))
|
||||
})?),
|
||||
};
|
||||
let parameters = normalize_mcp_parameters(&wire.name, parameters)?;
|
||||
let name = model_tool_name(&wire.name);
|
||||
let definition = ToolDefinition {
|
||||
name: name.clone(),
|
||||
@@ -477,6 +478,43 @@ pub fn dynamic_mcp(
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn normalize_mcp_parameters(tool_name: &str, mut parameters: Value) -> Result<Value> {
|
||||
let schema = parameters
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| invalid_mcp_parameters(tool_name))?;
|
||||
match schema.get("type") {
|
||||
Some(Value::String(schema_type)) if schema_type == "object" => return Ok(parameters),
|
||||
Some(_) => return Err(invalid_mcp_parameters(tool_name)),
|
||||
None => {}
|
||||
}
|
||||
let object_only_union = ["anyOf", "oneOf"].into_iter().any(|keyword| {
|
||||
schema
|
||||
.get(keyword)
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|branches| {
|
||||
!branches.is_empty()
|
||||
&& branches.iter().all(|branch| {
|
||||
branch
|
||||
.as_object()
|
||||
.and_then(|branch| branch.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("object")
|
||||
})
|
||||
})
|
||||
});
|
||||
if !object_only_union {
|
||||
return Err(invalid_mcp_parameters(tool_name));
|
||||
}
|
||||
schema.insert("type".into(), Value::String("object".into()));
|
||||
Ok(parameters)
|
||||
}
|
||||
|
||||
fn invalid_mcp_parameters(tool_name: &str) -> Error {
|
||||
Error::Protocol(format!(
|
||||
"MCP tool {tool_name} input schema must describe an object"
|
||||
))
|
||||
}
|
||||
|
||||
fn model_tool_name(name: &str) -> String {
|
||||
name.chars()
|
||||
.map(|character| {
|
||||
@@ -575,6 +613,115 @@ mod tests {
|
||||
.contains("duplicate MCP tool name after normalization: server_name-tool"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_mcp_normalizes_cursor_object_union_without_mutating_wire_schema() {
|
||||
let original_schema = serde_json::json!({
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"rootPath": { "type": "string", "minLength": 1 }
|
||||
},
|
||||
"required": ["rootPath"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"rootPaths": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "minLength": 1 },
|
||||
"minItems": 1
|
||||
}
|
||||
},
|
||||
"required": ["rootPaths"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
});
|
||||
let original_json = original_schema.to_string();
|
||||
let mut tool = direct_mcp_tool("cursor-app-control-move_agent_to_cloned_root");
|
||||
tool.input_schema_json = Some(original_json.clone());
|
||||
let request = pb::AgentRunRequest {
|
||||
mcp_tools: Some(pb::McpTools {
|
||||
mcp_tools: vec![tool],
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let tools = dynamic_mcp(&request, &pb::RequestContext::default()).unwrap();
|
||||
let (wire, definition) = tools
|
||||
.get("cursor-app-control-move_agent_to_cloned_root")
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(definition.parameters["type"], "object");
|
||||
assert_eq!(definition.parameters["anyOf"], original_schema["anyOf"]);
|
||||
assert_eq!(
|
||||
wire.input_schema_json.as_deref(),
|
||||
Some(original_json.as_str())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_mcp_preserves_valid_object_schema() {
|
||||
let original_schema = serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": { "type": "string" }
|
||||
},
|
||||
"required": ["query"],
|
||||
"additionalProperties": false
|
||||
});
|
||||
let mut tool = direct_mcp_tool("search");
|
||||
tool.input_schema_json = Some(original_schema.to_string());
|
||||
let request = pb::AgentRunRequest {
|
||||
mcp_tools: Some(pb::McpTools {
|
||||
mcp_tools: vec![tool],
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let tools = dynamic_mcp(&request, &pb::RequestContext::default()).unwrap();
|
||||
let (_, definition) = tools.get("search").unwrap();
|
||||
|
||||
assert_eq!(definition.parameters, original_schema);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_mcp_rejects_schemas_that_are_not_provably_objects() {
|
||||
let invalid_schemas = [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!({ "type": "string" }),
|
||||
serde_json::json!({ "properties": { "query": { "type": "string" } } }),
|
||||
serde_json::json!({
|
||||
"anyOf": [
|
||||
{ "type": "object" },
|
||||
{ "type": "string" }
|
||||
]
|
||||
}),
|
||||
];
|
||||
|
||||
for schema in invalid_schemas {
|
||||
let mut tool = direct_mcp_tool("unsafe_schema");
|
||||
tool.input_schema_json = Some(schema.to_string());
|
||||
let request = pb::AgentRunRequest {
|
||||
mcp_tools: Some(pb::McpTools {
|
||||
mcp_tools: vec![tool],
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let error = dynamic_mcp(&request, &pb::RequestContext::default()).unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("MCP tool unsafe_schema input schema must describe an object"),
|
||||
"unexpected error for {schema}: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn meta_mcp_routes_projects_descriptor_routing_without_runtime_discovery() {
|
||||
let context = pb::RequestContext {
|
||||
|
||||
@@ -129,11 +129,19 @@ impl CursorSession {
|
||||
checkpoint_worker_open = false;
|
||||
}
|
||||
Input::Completion(completion) => {
|
||||
self.forward_completion(completion, &mut completions)
|
||||
.await?;
|
||||
if let Some(completion) = self
|
||||
.forward_completion(completion, &mut completions)
|
||||
.await?
|
||||
{
|
||||
ready.push_back(completion);
|
||||
}
|
||||
}
|
||||
Input::CompletionResult(Some(result)) => {
|
||||
self.forward_completion(result?, &mut completions).await?;
|
||||
if let Some(completion) =
|
||||
self.forward_completion(result?, &mut completions).await?
|
||||
{
|
||||
ready.push_back(completion);
|
||||
}
|
||||
}
|
||||
Input::CompletionResult(None) => {
|
||||
return Err(Error::Protocol("tool result channel closed".into()));
|
||||
@@ -578,7 +586,7 @@ impl CursorSession {
|
||||
&self,
|
||||
mut completion: ToolCompletion,
|
||||
completions: &mut HashMap<String, ToolCompletion>,
|
||||
) -> Result<()> {
|
||||
) -> Result<Option<ToolCompletion>> {
|
||||
if let Some(image) = completion.take_read_image() {
|
||||
let blob_id = self.store.put_blob(&image.data, &[]).await?;
|
||||
completion.persist_read_image(&blob_id, &image)?;
|
||||
@@ -600,7 +608,14 @@ impl CursorSession {
|
||||
.commands
|
||||
.send(ClientCommand::ToolResult(result.clone()))
|
||||
.await
|
||||
.map_err(|_| Error::RunNotFound(self.context.request_id.clone()))
|
||||
.map_err(|_| Error::RunNotFound(self.context.request_id.clone()))?;
|
||||
let Some(dispatched) = self.tools.continue_after(&result.call_id).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
for message in dispatched.messages {
|
||||
self.handle.emit(&message)?;
|
||||
}
|
||||
Ok(dispatched.completion)
|
||||
}
|
||||
|
||||
async fn forward_injection(&mut self, action: pb::InjectContextAction) -> Result<()> {
|
||||
|
||||
@@ -20,6 +20,13 @@ pub(crate) fn path(call: &ToolCall) -> Result<String> {
|
||||
string(call, field)
|
||||
}
|
||||
|
||||
pub(crate) fn execution_path(call: &ToolCall) -> Result<Option<String>> {
|
||||
match normalized(&call.name).as_str() {
|
||||
"write" | "strreplace" | "editnotebook" => path(call).map(Some),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn after_read(
|
||||
call: &ToolCall,
|
||||
result: &pb::ReadResult,
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
pub mod codec;
|
||||
mod dispatch;
|
||||
pub(crate) mod edit;
|
||||
pub(crate) mod result;
|
||||
pub mod runtime;
|
||||
mod schedule;
|
||||
pub(crate) mod stream;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use crate::{
|
||||
model::{CanonicalMessage, MessageContent, Role, ToolCall},
|
||||
@@ -14,6 +22,7 @@ use crate::{
|
||||
};
|
||||
|
||||
use self::result::{ToolCompletion, ToolResultSender};
|
||||
use self::schedule::{DeferredEdit, EditSchedule};
|
||||
use super::{interaction, proto::agent::v1 as pb};
|
||||
use runtime::{CursorToolRuntime, ExecContext};
|
||||
|
||||
@@ -23,6 +32,7 @@ pub struct ToolDispatcher {
|
||||
results: ToolResultSender,
|
||||
search: WebSearch,
|
||||
fetch: WebFetch,
|
||||
edit_schedule: Arc<Mutex<EditSchedule>>,
|
||||
}
|
||||
|
||||
pub struct DispatchedTool {
|
||||
@@ -54,6 +64,7 @@ impl ToolDispatcher {
|
||||
results,
|
||||
search: WebSearch::built_in(),
|
||||
fetch: WebFetch::built_in(),
|
||||
edit_schedule: Arc::new(Mutex::new(EditSchedule::default())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,20 +85,62 @@ impl ToolDispatcher {
|
||||
if state.completed.contains(&call.call_id) {
|
||||
continue;
|
||||
}
|
||||
let message_index = first_tool_index + position;
|
||||
let publish_started = !state.started.contains(&call.call_id);
|
||||
let edit_path = if dynamic_mcp.contains_key(&call.name) {
|
||||
None
|
||||
} else {
|
||||
edit::execution_path(call)?
|
||||
};
|
||||
if let Some(path) = edit_path {
|
||||
let next = self.edit_schedule.lock().await.start_or_defer(
|
||||
path,
|
||||
DeferredEdit {
|
||||
call: call.clone(),
|
||||
message_index,
|
||||
publish_started,
|
||||
context: context.clone(),
|
||||
},
|
||||
);
|
||||
let Some(next) = next else {
|
||||
continue;
|
||||
};
|
||||
dispatched.push(
|
||||
self.start(
|
||||
&next.call,
|
||||
next.message_index,
|
||||
next.publish_started,
|
||||
dynamic_mcp,
|
||||
&next.context,
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
dispatched.push(
|
||||
self.start(
|
||||
call,
|
||||
first_tool_index + position,
|
||||
!state.started.contains(&call.call_id),
|
||||
dynamic_mcp,
|
||||
context,
|
||||
)
|
||||
.await?,
|
||||
self.start(call, message_index, publish_started, dynamic_mcp, context)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
Ok(dispatched)
|
||||
}
|
||||
|
||||
pub(crate) async fn continue_after(&self, call_id: &str) -> Result<Option<DispatchedTool>> {
|
||||
let next = self.edit_schedule.lock().await.complete(call_id)?;
|
||||
let Some(next) = next else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.start(
|
||||
&next.call,
|
||||
next.message_index,
|
||||
next.publish_started,
|
||||
&BTreeMap::new(),
|
||||
&next.context,
|
||||
)
|
||||
.await
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
async fn start(
|
||||
&self,
|
||||
call: &ToolCall,
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
use crate::{model::ToolCall, Error, Result};
|
||||
|
||||
use super::runtime::ExecContext;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct EditSchedule {
|
||||
paths: HashMap<String, EditPathQueue>,
|
||||
active_paths: HashMap<String, String>,
|
||||
}
|
||||
|
||||
struct EditPathQueue {
|
||||
active_call_id: String,
|
||||
waiting: VecDeque<DeferredEdit>,
|
||||
}
|
||||
|
||||
pub(super) struct DeferredEdit {
|
||||
pub call: ToolCall,
|
||||
pub message_index: usize,
|
||||
pub publish_started: bool,
|
||||
pub context: ExecContext,
|
||||
}
|
||||
|
||||
impl EditSchedule {
|
||||
pub fn start_or_defer(&mut self, path: String, edit: DeferredEdit) -> Option<DeferredEdit> {
|
||||
if let Some(queue) = self.paths.get_mut(&path) {
|
||||
queue.waiting.push_back(edit);
|
||||
return None;
|
||||
}
|
||||
self.active_paths
|
||||
.insert(edit.call.call_id.clone(), path.clone());
|
||||
self.paths.insert(
|
||||
path,
|
||||
EditPathQueue {
|
||||
active_call_id: edit.call.call_id.clone(),
|
||||
waiting: VecDeque::new(),
|
||||
},
|
||||
);
|
||||
Some(edit)
|
||||
}
|
||||
|
||||
pub fn complete(&mut self, call_id: &str) -> Result<Option<DeferredEdit>> {
|
||||
let Some(path) = self.active_paths.remove(call_id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let queue = self.paths.get_mut(&path).ok_or_else(|| {
|
||||
Error::Protocol(format!("active edit path disappeared for call {call_id}"))
|
||||
})?;
|
||||
if queue.active_call_id != call_id {
|
||||
return Err(Error::Protocol(format!(
|
||||
"edit path is active for {}, not {call_id}",
|
||||
queue.active_call_id
|
||||
)));
|
||||
}
|
||||
match queue.waiting.pop_front() {
|
||||
Some(next) => {
|
||||
queue.active_call_id = next.call.call_id.clone();
|
||||
self.active_paths.insert(next.call.call_id.clone(), path);
|
||||
Ok(Some(next))
|
||||
}
|
||||
None => {
|
||||
self.paths.remove(&path);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn edit_call(index: usize, call_id: &str, path: &str, old: &str, new: &str) -> ToolCall {
|
||||
ToolCall {
|
||||
index,
|
||||
call_id: call_id.into(),
|
||||
model_call_id: "model:0".into(),
|
||||
name: "StrReplace".into(),
|
||||
arguments_text: String::new(),
|
||||
arguments: json!({
|
||||
"path": path,
|
||||
"old_string": old,
|
||||
"new_string": new,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn same_path_edits_start_one_at_a_time() {
|
||||
let runtime = CursorToolRuntime::default();
|
||||
let dispatcher = ToolDispatcher::new(runtime.clone());
|
||||
let calls = [
|
||||
edit_call(0, "first", "/tmp/a.txt", "left", "LEFT"),
|
||||
edit_call(1, "second", "/tmp/a.txt", "right", "RIGHT"),
|
||||
edit_call(2, "other", "/tmp/b.txt", "other", "OTHER"),
|
||||
];
|
||||
|
||||
let dispatched = dispatcher
|
||||
.start_batch(
|
||||
&calls,
|
||||
ToolBatchState {
|
||||
completed: &HashSet::new(),
|
||||
started: &HashSet::new(),
|
||||
response_text: "",
|
||||
response_thinking: "",
|
||||
},
|
||||
&[],
|
||||
&BTreeMap::new(),
|
||||
&ExecContext::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(dispatched.len(), 2);
|
||||
assert_eq!(exec(&dispatched[0]).exec_id, "first");
|
||||
assert_eq!(exec(&dispatched[1]).exec_id, "other");
|
||||
|
||||
let mut file = "left right\n".to_string();
|
||||
let first_write = advance_read(&runtime, exec(&dispatched[0]).id, &file).await;
|
||||
file = write_text(&first_write);
|
||||
assert_eq!(file, "LEFT right\n");
|
||||
complete_write(&runtime, &first_write).await;
|
||||
|
||||
let second = dispatcher
|
||||
.continue_after("first")
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("second same-path edit should start after the first completes");
|
||||
assert_eq!(exec(&second).exec_id, "second");
|
||||
let second_write = advance_read(&runtime, exec(&second).id, &file).await;
|
||||
file = write_text(&second_write);
|
||||
assert_eq!(file, "LEFT RIGHT\n");
|
||||
complete_write(&runtime, &second_write).await;
|
||||
assert!(dispatcher.continue_after("second").await.unwrap().is_none());
|
||||
}
|
||||
|
||||
fn exec(dispatched: &DispatchedTool) -> &pb::ExecServerMessage {
|
||||
dispatched
|
||||
.messages
|
||||
.iter()
|
||||
.find_map(|message| match message.message.as_ref() {
|
||||
Some(pb::agent_server_message::Message::ExecServerMessage(exec)) => Some(exec),
|
||||
_ => None,
|
||||
})
|
||||
.expect("dispatched edit should contain an Exec request")
|
||||
}
|
||||
|
||||
async fn advance_read(
|
||||
runtime: &CursorToolRuntime,
|
||||
id: u32,
|
||||
content: &str,
|
||||
) -> pb::ExecServerMessage {
|
||||
let event = codec::client_event(
|
||||
&pb::ExecClientMessage {
|
||||
id,
|
||||
message: Some(pb::exec_client_message::Message::ReadResult(
|
||||
pb::ReadResult {
|
||||
result: Some(pb::read_result::Result::Success(pb::ReadSuccess {
|
||||
output: Some(pb::read_success::Output::Content(content.into())),
|
||||
..Default::default()
|
||||
})),
|
||||
},
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
runtime,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let codec::ClientExecEvent::Message(message) = event else {
|
||||
panic!("edit read should advance to a write")
|
||||
};
|
||||
let Some(pb::agent_server_message::Message::ExecServerMessage(exec)) = message.message else {
|
||||
panic!("edit read should emit an Exec write request")
|
||||
};
|
||||
exec
|
||||
}
|
||||
|
||||
fn write_text(exec: &pb::ExecServerMessage) -> String {
|
||||
let Some(pb::exec_server_message::Message::WriteArgs(args)) = exec.message.as_ref() else {
|
||||
panic!("expected WriteArgs")
|
||||
};
|
||||
args.file_text.clone()
|
||||
}
|
||||
|
||||
async fn complete_write(runtime: &CursorToolRuntime, exec: &pb::ExecServerMessage) {
|
||||
let Some(pb::exec_server_message::Message::WriteArgs(args)) = exec.message.as_ref() else {
|
||||
panic!("expected WriteArgs")
|
||||
};
|
||||
let event = codec::client_event(
|
||||
&pb::ExecClientMessage {
|
||||
id: exec.id,
|
||||
message: Some(pb::exec_client_message::Message::WriteResult(
|
||||
pb::WriteResult {
|
||||
result: Some(pb::write_result::Result::Success(pb::WriteSuccess {
|
||||
path: args.path.clone(),
|
||||
..Default::default()
|
||||
})),
|
||||
},
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
runtime,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(event, codec::ClientExecEvent::Completed(_)));
|
||||
}
|
||||
Reference in new issue
Block a user