1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//! `browser_research` MCP tool implementation with elite terminal design pattern
//!
//! Action-based interface: EXEC/READ/LIST/KILL
//! Session management with connection isolation
//! Timeout with background continuation
use crate::research::ResearchRegistry;
use crate::utils::{DeepResearch, ResearchOptions};
use kodegen_mcp_schema::browser::{
BrowserResearchAction, BrowserResearchArgs, BrowserResearchOutput,
ResearchSource, BROWSER_RESEARCH,
ResearchPrompts,
};
use kodegen_mcp_schema::{McpError, Tool, ToolExecutionContext, ToolResponse};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::OnceCell;
// =============================================================================
// TOOL IMPLEMENTATION
// =============================================================================
#[derive(Clone)]
pub struct BrowserResearchTool {
browser_manager: Arc<crate::BrowserManager>,
registry: Arc<OnceCell<ResearchRegistry>>,
}
impl BrowserResearchTool {
pub fn new(browser_manager: Arc<crate::BrowserManager>) -> Self {
Self {
browser_manager,
registry: Arc::new(OnceCell::new()),
}
}
pub async fn get_registry(&self) -> ResearchRegistry {
self.registry
.get_or_init(|| async { ResearchRegistry::new() })
.await
.clone()
}
}
impl Tool for BrowserResearchTool {
type Args = BrowserResearchArgs;
type Prompts = ResearchPrompts;
fn name() -> &'static str {
BROWSER_RESEARCH
}
fn description() -> &'static str {
"Perform deep web research with session management.\n\n\
Actions:\n\
- RESEARCH: Start new research (spawns background task)\n\
- READ: Check progress of active research\n\
- LIST: Show all active research sessions\n\
- KILL: Terminate a running research session (destroys slot)\n\n\
Example: browser_research({\"action\": \"RESEARCH\", \"query\": \"Rust async patterns\", \"session\": 0})"
}
fn read_only() -> bool {
false
}
fn destructive() -> bool {
false
}
fn idempotent() -> bool {
false
}
fn open_world() -> bool {
true
}
async fn execute(
&self,
args: Self::Args,
ctx: ToolExecutionContext,
) -> Result<ToolResponse<BrowserResearchOutput>, McpError> {
let registry = self.get_registry().await;
let connection_id = ctx.connection_id().unwrap_or("default");
match args.action {
BrowserResearchAction::Research => {
// Validate query
let query = args.query.ok_or_else(|| {
McpError::invalid_arguments("query is required for RESEARCH action")
})?;
if query.trim().is_empty() {
return Err(McpError::invalid_arguments("Research query cannot be empty"));
}
// Build research options
let options = Some(ResearchOptions {
max_pages: args.max_pages,
max_depth: args.max_depth,
search_engine: args.search_engine.clone(),
include_links: args.include_links,
extract_tables: args.extract_tables,
extract_images: args.extract_images,
timeout_seconds: args.timeout_seconds,
});
// Create DeepResearch instance
let research = DeepResearch::new(
self.browser_manager.clone(),
args.temperature,
args.max_tokens,
);
// Create new session (always fresh for RESEARCH action)
let session = registry
.create(connection_id, args.session, research, query.clone(), options)
.await;
// Start research in background
session.start().await.map_err(McpError::Other)?;
// Fire-and-forget: return immediately
if args.await_completion_ms == 0 {
let output = BrowserResearchOutput {
session: args.session,
status: "running".to_string(),
query,
pages_analyzed: 0,
max_pages: args.max_pages,
completed: false,
summary: None,
key_findings: None,
sources: vec![],
error: None,
};
return Ok(ToolResponse::new(
"Research started in background. Use READ to check progress.",
output,
));
}
// Wait with timeout
let timeout_duration = Duration::from_millis(args.await_completion_ms);
let wait_result = tokio::time::timeout(timeout_duration, async {
// Poll for completion
loop {
if session.is_complete().await {
break;
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
})
.await;
// Read current state (whether timed out or completed)
let session_output = session.read(args.session).await;
// Convert to output format using schema types
let sources: Vec<ResearchSource> = session_output
.results
.iter()
.map(|r| ResearchSource {
url: r.url.clone(),
title: Some(r.title.clone()),
summary: Some(r.summary.clone()),
})
.collect();
let display = if wait_result.is_ok() {
session_output.summary.clone()
} else {
format!(
"Research timeout after {}ms. {} results so far. Research continues in background.",
args.await_completion_ms,
session_output.results.len()
)
};
let output = BrowserResearchOutput {
session: args.session,
status: if session_output.completed { "completed" } else { "running" }.to_string(),
query: session_output.query,
pages_analyzed: session_output.results.len(),
max_pages: args.max_pages,
completed: session_output.completed,
summary: if session_output.completed { Some(session_output.summary.clone()) } else { None },
key_findings: None,
sources,
error: None,
};
Ok(ToolResponse::new(display, output))
}
BrowserResearchAction::Read => {
// Get existing session
let session = registry
.get(connection_id, args.session)
.await
.ok_or_else(|| {
McpError::invalid_arguments(format!(
"Research session {} not found",
args.session
))
})?;
// Read current state
let session_output = session.read(args.session).await;
// Opportunistic cleanup if session completed
if session_output.completed {
let registry_clone = registry.clone();
let conn_id = connection_id.to_string();
tokio::spawn(async move {
let cleaned = registry_clone.cleanup_completed(&conn_id).await;
if cleaned > 0 {
tracing::info!(
"Cleaned up {} completed session(s) for connection {}",
cleaned,
conn_id
);
}
});
}
// Convert to output format using schema types
let sources: Vec<ResearchSource> = session_output
.results
.iter()
.map(|r| ResearchSource {
url: r.url.clone(),
title: Some(r.title.clone()),
summary: Some(r.summary.clone()),
})
.collect();
let output = BrowserResearchOutput {
session: args.session,
status: if session_output.completed { "completed" } else { "running" }.to_string(),
query: session_output.query.clone(),
pages_analyzed: session_output.results.len(),
max_pages: args.max_pages,
completed: session_output.completed,
summary: if session_output.completed { Some(session_output.summary.clone()) } else { None },
key_findings: None,
sources,
error: None,
};
Ok(ToolResponse::new(session_output.summary, output))
}
BrowserResearchAction::List => {
// List all sessions for this connection
let list_output = registry
.list(connection_id)
.await
.map_err(McpError::Other)?;
// Build display string with session info
let display = if list_output.sessions.is_empty() {
format!("No active research sessions for connection {}", list_output.connection_id)
} else {
let sessions_info: Vec<String> = list_output.sessions.iter()
.map(|s| format!(
"Session {}: query='{}', completed={}, results={}",
s.session, s.query, s.completed, s.results_count
))
.collect();
format!(
"Active research sessions for connection {}:\n{}",
list_output.connection_id,
sessions_info.join("\n")
)
};
let output = BrowserResearchOutput {
session: args.session,
status: "list".to_string(),
query: String::new(),
pages_analyzed: list_output.total,
max_pages: 0,
completed: true,
summary: Some(display.clone()),
key_findings: None,
sources: vec![],
error: None,
};
Ok(ToolResponse::new(display, output))
}
BrowserResearchAction::Kill => {
// Get existing session
let session = registry
.get(connection_id, args.session)
.await
.ok_or_else(|| {
McpError::invalid_arguments(format!(
"Research session {} not found",
args.session
))
})?;
// Kill the session
session.kill().await.map_err(McpError::Other)?;
// Remove from registry
registry.remove(connection_id, args.session).await;
let message = format!("Research session {} terminated", args.session);
let output = BrowserResearchOutput {
session: args.session,
status: "killed".to_string(),
query: String::new(),
pages_analyzed: 0,
max_pages: 0,
completed: true,
summary: None,
key_findings: None,
sources: vec![],
error: None,
};
Ok(ToolResponse::new(message, output))
}
}
}
}