1#![forbid(unsafe_code)]
3
4use minco_project_view::{EvidenceLane, PROJECT_VIEW_SCHEMA_VERSION, ProjectView};
5use rmcp::{
6 ErrorData, ServiceExt,
7 handler::server::wrapper::{Json, Parameters},
8 model::Tool,
9 schemars, tool, tool_router,
10};
11use serde::{Deserialize, Serialize};
12use serde_json::{Value, json};
13use std::{
14 io,
15 pin::Pin,
16 sync::Arc,
17 task::{Context, Poll},
18};
19use tokio::io::{AsyncRead, ReadBuf};
20
21pub const DEFAULT_MAX_MCP_MESSAGE_BYTES: usize = 256 * 1024;
22
23#[derive(Debug, thiserror::Error)]
24pub enum StdioServerError {
25 #[error("MCP stdio initialization failed: {0}")]
26 Initialize(#[source] Box<rmcp::service::ServerInitializeError>),
27 #[error("MCP stdio task failed: {0}")]
28 Join(#[from] tokio::task::JoinError),
29}
30
31impl From<rmcp::service::ServerInitializeError> for StdioServerError {
32 fn from(error: rmcp::service::ServerInitializeError) -> Self {
33 Self::Initialize(Box::new(error))
34 }
35}
36
37#[derive(Debug)]
38pub struct BoundedMessageReader<R> {
39 inner: R,
40 max_line_bytes: usize,
41 current_line_bytes: usize,
42}
43
44impl<R> BoundedMessageReader<R> {
45 #[must_use]
46 pub const fn new(inner: R, max_line_bytes: usize) -> Self {
47 Self {
48 inner,
49 max_line_bytes,
50 current_line_bytes: 0,
51 }
52 }
53}
54
55impl<R: AsyncRead + Unpin> AsyncRead for BoundedMessageReader<R> {
56 fn poll_read(
57 mut self: Pin<&mut Self>,
58 context: &mut Context<'_>,
59 destination: &mut ReadBuf<'_>,
60 ) -> Poll<io::Result<()>> {
61 if destination.remaining() == 0 {
62 return Poll::Ready(Ok(()));
63 }
64
65 let mut storage = [0_u8; 8 * 1024];
66 let capacity = destination.remaining().min(storage.len());
67 let mut bounded = ReadBuf::new(&mut storage[..capacity]);
68 match Pin::new(&mut self.inner).poll_read(context, &mut bounded) {
69 Poll::Pending => Poll::Pending,
70 Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
71 Poll::Ready(Ok(())) => {
72 for byte in bounded.filled() {
73 self.current_line_bytes = self.current_line_bytes.saturating_add(1);
74 if self.current_line_bytes > self.max_line_bytes {
75 return Poll::Ready(Err(io::Error::new(
76 io::ErrorKind::InvalidData,
77 format!(
78 "MCP message exceeds max_message_bytes={}",
79 self.max_line_bytes
80 ),
81 )));
82 }
83 if *byte == b'\n' {
84 self.current_line_bytes = 0;
85 }
86 }
87 destination.put_slice(bounded.filled());
88 Poll::Ready(Ok(()))
89 }
90 }
91 }
92}
93
94#[derive(Debug, Clone)]
95pub struct MincoMcp {
96 view: Arc<ProjectView>,
97}
98
99#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
100#[serde(deny_unknown_fields)]
101pub struct OperationExplainInput {
102 pub operation_id: String,
104}
105
106#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
107#[serde(deny_unknown_fields)]
108pub struct EmptyInput {}
109
110#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
111#[serde(deny_unknown_fields)]
112pub struct TaskReadinessInput {
113 pub task_id: Option<String>,
115}
116
117#[derive(Debug, Clone, Copy, Deserialize, schemars::JsonSchema)]
118#[serde(rename_all = "snake_case")]
119pub enum EvidenceLaneInput {
120 Source,
121 LocalVerification,
122 HostedVerification,
123 Deployment,
124 Runtime,
125 Review,
126}
127
128impl From<EvidenceLaneInput> for EvidenceLane {
129 fn from(value: EvidenceLaneInput) -> Self {
130 match value {
131 EvidenceLaneInput::Source => Self::Source,
132 EvidenceLaneInput::LocalVerification => Self::LocalVerification,
133 EvidenceLaneInput::HostedVerification => Self::HostedVerification,
134 EvidenceLaneInput::Deployment => Self::Deployment,
135 EvidenceLaneInput::Runtime => Self::Runtime,
136 EvidenceLaneInput::Review => Self::Review,
137 }
138 }
139}
140
141#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
142#[serde(deny_unknown_fields)]
143pub struct EvidenceInput {
144 pub lane: Option<EvidenceLaneInput>,
146}
147
148#[tool_router(server_handler)]
149impl MincoMcp {
150 #[must_use]
151 pub fn new(view: ProjectView) -> Self {
152 Self {
153 view: Arc::new(view),
154 }
155 }
156
157 #[must_use]
158 pub fn tool_catalog() -> Vec<Tool> {
159 Self::tool_router().list_all()
160 }
161
162 fn bounded<T: Serialize>(&self, kind: &'static str, data: T) -> Result<Json<Value>, ErrorData> {
163 let value = json!({
164 "schema_version": PROJECT_VIEW_SCHEMA_VERSION,
165 "kind": kind,
166 "data": data,
167 });
168 let prospective_result = rmcp::model::CallToolResult::structured(value.clone());
169 let bytes = serde_json::to_vec(&prospective_result).map_err(|_| {
170 ErrorData::internal_error("Minco MCP response serialization failed", None)
171 })?;
172 if bytes.len().saturating_add(DEFAULT_MAX_MCP_MESSAGE_BYTES)
173 > self.view.limits.max_response_bytes
174 {
175 return Err(ErrorData::internal_error(
176 "Minco MCP response exceeds its configured byte limit",
177 None,
178 ));
179 }
180 Ok(Json(value))
181 }
182
183 #[tool(
184 name = "minco.project_view",
185 description = "Return the complete bounded repository-native Minco ProjectView.",
186 annotations(
187 read_only_hint = true,
188 destructive_hint = false,
189 idempotent_hint = true,
190 open_world_hint = false
191 )
192 )]
193 fn project_view(
194 &self,
195 Parameters(_input): Parameters<EmptyInput>,
196 ) -> Result<Json<Value>, ErrorData> {
197 self.bounded("project_view", self.view.as_ref())
198 }
199
200 #[tool(
201 name = "minco.project_summary",
202 description = "Return the ProjectView identity, derived summary, limits, input usage, and diagnostics.",
203 annotations(
204 read_only_hint = true,
205 destructive_hint = false,
206 idempotent_hint = true,
207 open_world_hint = false
208 )
209 )]
210 fn project_summary(
211 &self,
212 Parameters(_input): Parameters<EmptyInput>,
213 ) -> Result<Json<Value>, ErrorData> {
214 self.bounded(
215 "project_summary",
216 json!({
217 "project": &self.view.project,
218 "summary": &self.view.summary,
219 "limits": &self.view.limits,
220 "input_usage": &self.view.input_usage,
221 "diagnostics": &self.view.diagnostics,
222 }),
223 )
224 }
225
226 #[tool(
227 name = "minco.operation_explain",
228 description = "Explain one declared OpenAPI operation by exact operationId without invoking it.",
229 annotations(
230 read_only_hint = true,
231 destructive_hint = false,
232 idempotent_hint = true,
233 open_world_hint = false
234 )
235 )]
236 fn operation_explain(
237 &self,
238 Parameters(input): Parameters<OperationExplainInput>,
239 ) -> Result<Json<Value>, ErrorData> {
240 self.bounded(
241 "operation_explain",
242 json!({
243 "operation_id": input.operation_id,
244 "found": self.view.operation(&input.operation_id).is_some(),
245 "operation": self.view.operation(&input.operation_id),
246 }),
247 )
248 }
249
250 #[tool(
251 name = "minco.task_readiness",
252 description = "Return derived readiness for one exact task ID or all repository tasks.",
253 annotations(
254 read_only_hint = true,
255 destructive_hint = false,
256 idempotent_hint = true,
257 open_world_hint = false
258 )
259 )]
260 fn task_readiness(
261 &self,
262 Parameters(input): Parameters<TaskReadinessInput>,
263 ) -> Result<Json<Value>, ErrorData> {
264 match input.task_id {
265 Some(task_id) => self.bounded(
266 "task_readiness",
267 json!({
268 "task_id": task_id,
269 "found": self.view.task(&task_id).is_some(),
270 "task": self.view.task(&task_id),
271 }),
272 ),
273 None => self.bounded("task_readiness", &self.view.task_readiness),
274 }
275 }
276
277 #[tool(
278 name = "minco.evidence",
279 description = "Return ProjectView evidence while preserving source, local, hosted, deployment, runtime, and review as independent lanes.",
280 annotations(
281 read_only_hint = true,
282 destructive_hint = false,
283 idempotent_hint = true,
284 open_world_hint = false
285 )
286 )]
287 fn evidence(
288 &self,
289 Parameters(input): Parameters<EvidenceInput>,
290 ) -> Result<Json<Value>, ErrorData> {
291 match input.lane {
292 Some(lane) => {
293 let lane = EvidenceLane::from(lane);
294 self.bounded(
295 "evidence",
296 json!({
297 "lane": lane,
298 "items": self.view.evidence.get(&lane).cloned().unwrap_or_default(),
299 }),
300 )
301 }
302 None => self.bounded("evidence", &self.view.evidence),
303 }
304 }
305
306 #[tool(
307 name = "minco.feedback_context",
308 description = "Return bounded Feedback capability metadata and operation IDs; never records, attachments, credentials, or provider access.",
309 annotations(
310 read_only_hint = true,
311 destructive_hint = false,
312 idempotent_hint = true,
313 open_world_hint = false
314 )
315 )]
316 fn feedback_context(
317 &self,
318 Parameters(_input): Parameters<EmptyInput>,
319 ) -> Result<Json<Value>, ErrorData> {
320 self.bounded("feedback_context", &self.view.feedback)
321 }
322}
323
324pub async fn serve_stdio(view: ProjectView) -> Result<(), StdioServerError> {
325 let transport = (
326 BoundedMessageReader::new(tokio::io::stdin(), DEFAULT_MAX_MCP_MESSAGE_BYTES),
327 tokio::io::stdout(),
328 );
329 let service = MincoMcp::new(view).serve(transport).await?;
330 service.waiting().await?;
331 Ok(())
332}