@sigit / si Mirror · read-only
Fork 0

Mirror of github.com/getsigit/si.

Mirrored from https://github.com/getsigit/si.git

Synced Nov 24, 09:30 UTC

1 //! `si` as an MCP server over stdio.
2 //!
3 //! `si mcp` stops being a one-shot command and becomes a long-lived
4 //! [Model Context Protocol](https://modelcontextprotocol.io) server, so an
5 //! agent can do what the CLI does: list repos, read and search code, triage
6 //! issues, open pull requests, drive Cloud Sessions.
7 //!
8 //! sigit.si already serves a remote MCP endpoint at `/api/v1/mcp` (it's what
9 //! [`sigit_si_api::mcp`] calls into), so a local server only earns its keep by
10 //! doing what a remote one can't:
11 //!
12 //! - **No auth to configure.** It reuses the token `si auth login` stored, so
13 //! an editor points at a binary and is done — no OAuth dance, no PAT pasted
14 //! into a config file.
15 //! - **It knows where you're standing.** Every repo-scoped tool takes `repo`
16 //! as an *optional* argument and falls back to the sigit.si remote of the
17 //! working directory, the same way the CLI does. `create_pull_request`
18 //! likewise defaults `head` to the checked-out branch.
19 //! - **It reaches the whole CLI.** Cloud Sessions, webhooks, billing, and repo
20 //! creation are plain REST that the remote MCP endpoint doesn't expose.
21 //!
22 //! Tools call the same [`sigit_si_api`] methods the command handlers do,
23 //! skipping the `ui` layer entirely: stdout is the JSON-RPC channel, so
24 //! nothing here may print to it. Logging already goes to stderr (see `main`).
25 //!
26 //! Toolsets and `--read-only` exist because trimming the tool list keeps the
27 //! model's choice sharp and its context small.
28
29 use {
30 crate::{
31 cli::McpArgs,
32 context::Ctx,
33 git::{self, RepoSlug},
34 },
35 anyhow::{anyhow, Result},
36 rmcp::{
37 handler::server::{router::tool::ToolRouter, wrapper::Parameters, ServerHandler},
38 model::{CallToolResult, ContentBlock, Implementation, ServerCapabilities, ServerInfo},
39 tool, tool_handler, tool_router,
40 transport::stdio,
41 ErrorData, ServiceExt,
42 },
43 schemars::JsonSchema,
44 serde::Deserialize,
45 sigit_si_api::{Client, NewRepository, State},
46 };
47
48 /// The tool groups `--toolsets` selects from.
49 const TOOLSETS: [&str; 8] = [
50 "account", "repo", "issue", "pr", "code", "hook", "session", "billing",
51 ];
52
53 /// The sigit.si MCP server. Holds the same [`Ctx`] the command handlers get,
54 /// which is where the API client and working-directory repo resolution live.
55 pub struct SiMcpServer {
56 ctx: Ctx,
57 tool_router: ToolRouter<Self>,
58 }
59
60 impl SiMcpServer {
61 fn new(ctx: Ctx, tool_router: ToolRouter<Self>) -> Self {
62 Self { ctx, tool_router }
63 }
64
65 /// The API client, refusing early when there's no token rather than
66 /// letting every tool round-trip to a 401.
67 fn client(&self) -> Result<&Client, ErrorData> {
68 self.ctx
69 .require_token()
70 .map(|()| &self.ctx.client)
71 .map_err(|e| ErrorData::invalid_request(e.to_string(), None))
72 }
73
74 /// Resolve a tool's optional `repo` argument, falling back to the repo the
75 /// server was started in.
76 fn repo(&self, explicit: Option<String>) -> Result<String, ErrorData> {
77 self.ctx
78 .resolve_repo(explicit)
79 .map(|slug| slug.to_string())
80 .map_err(|e| ErrorData::invalid_request(e.to_string(), None))
81 }
82 }
83
84 /// Serialize a value into a one-block successful tool result.
85 fn json_result<T: serde::Serialize>(value: &T) -> Result<CallToolResult, ErrorData> {
86 Ok(CallToolResult::success(vec![ContentBlock::json(value)?]))
87 }
88
89 fn text_result(message: impl Into<String>) -> Result<CallToolResult, ErrorData> {
90 Ok(CallToolResult::success(vec![ContentBlock::text(
91 message.into(),
92 )]))
93 }
94
95 fn to_error_data(error: impl std::fmt::Display) -> ErrorData {
96 ErrorData::internal_error(error.to_string(), None)
97 }
98
99 /// Which issues or pull requests to list. An enum rather than a string so the
100 /// advertised schema tells the model what the choices are.
101 #[derive(Debug, Default, Clone, Copy, Deserialize, JsonSchema)]
102 #[serde(rename_all = "lowercase")]
103 enum StateArg {
104 #[default]
105 Open,
106 Closed,
107 Merged,
108 All,
109 }
110
111 impl From<StateArg> for State {
112 fn from(state: StateArg) -> Self {
113 match state {
114 StateArg::Open => State::Open,
115 StateArg::Closed => State::Closed,
116 StateArg::Merged => State::Merged,
117 StateArg::All => State::All,
118 }
119 }
120 }
121
122 /// The `repo` argument every repository-scoped tool shares.
123 #[derive(Debug, Deserialize, JsonSchema)]
124 struct RepoArgs {
125 /// Repository as OWNER/NAME. Defaults to the repository the server is
126 /// running in.
127 #[serde(default)]
128 repo: Option<String>,
129 }
130
131 // ---------------------------------------------------------------- account --
132
133 #[tool_router(router = account_router)]
134 impl SiMcpServer {
135 /// Show the signed-in sigit.si user: name, email, and plan.
136 #[tool(annotations(read_only_hint = true))]
137 async fn whoami(&self) -> Result<CallToolResult, ErrorData> {
138 let user = self.client()?.user().await.map_err(to_error_data)?;
139 json_result(&user)
140 }
141 }
142
143 // ------------------------------------------------------------------- repo --
144
145 #[derive(Debug, Deserialize, JsonSchema)]
146 struct ListRepositoriesArgs {
147 /// Case-insensitive substring of the owner or repository name. Omit to
148 /// list everything visible.
149 #[serde(default)]
150 query: Option<String>,
151 /// How many repositories to return. Defaults to the server's own limit.
152 #[serde(default)]
153 limit: Option<u32>,
154 }
155
156 #[derive(Debug, Deserialize, JsonSchema)]
157 struct CreateRepositoryArgs {
158 /// Name for the new repository.
159 name: String,
160 /// Whether the repository is private. Defaults to public.
161 #[serde(default)]
162 private: bool,
163 /// Optional one-line description.
164 #[serde(default)]
165 description: Option<String>,
166 }
167
168 #[tool_router(router = repo_router)]
169 impl SiMcpServer {
170 /// Search every repository the user can see by an owner/name substring.
171 /// Use this to find the OWNER/NAME other tools take.
172 #[tool(annotations(read_only_hint = true))]
173 async fn list_repositories(
174 &self,
175 Parameters(ListRepositoriesArgs { query, limit }): Parameters<ListRepositoriesArgs>,
176 ) -> Result<CallToolResult, ErrorData> {
177 let repos = self
178 .client()?
179 .search_repos(query.as_deref(), limit)
180 .await
181 .map_err(to_error_data)?;
182 json_result(&repos)
183 }
184
185 /// List the repositories the signed-in user owns, newest first.
186 #[tool(annotations(read_only_hint = true))]
187 async fn list_my_repositories(&self) -> Result<CallToolResult, ErrorData> {
188 let repos = self.client()?.repos().await.map_err(to_error_data)?;
189 json_result(&repos)
190 }
191
192 /// Identify the sigit.si repository and branch the server is running in.
193 /// Call this to find out what "the current repo" resolves to.
194 #[tool(annotations(read_only_hint = true))]
195 async fn current_repository(&self) -> Result<CallToolResult, ErrorData> {
196 let cwd = std::env::current_dir().map_err(to_error_data)?;
197 let slug: RepoSlug = self
198 .ctx
199 .resolve_repo(None)
200 .map_err(|e| ErrorData::invalid_request(e.to_string(), None))?;
201
202 json_result(&serde_json::json!({
203 "repo": slug.to_string(),
204 "owner": slug.owner,
205 "name": slug.name,
206 "branch": git::current_branch(&cwd),
207 "directory": cwd.display().to_string(),
208 }))
209 }
210
211 /// Create a new, empty repository to push to.
212 #[tool]
213 async fn create_repository(
214 &self,
215 Parameters(CreateRepositoryArgs {
216 name,
217 private,
218 description,
219 }): Parameters<CreateRepositoryArgs>,
220 ) -> Result<CallToolResult, ErrorData> {
221 let new_repo = NewRepository::new(name)
222 .private(private)
223 .description(description);
224 let repo = self
225 .client()?
226 .create_repo(&new_repo)
227 .await
228 .map_err(to_error_data)?;
229 json_result(&repo)
230 }
231 }
232
233 // ------------------------------------------------------------------ issue --
234
235 #[derive(Debug, Deserialize, JsonSchema)]
236 struct ListIssuesArgs {
237 /// Repository as OWNER/NAME. Defaults to the repository the server is
238 /// running in.
239 #[serde(default)]
240 repo: Option<String>,
241 /// Which issues to list. Defaults to open.
242 #[serde(default)]
243 state: StateArg,
244 /// Optional substring to match against issue titles and bodies.
245 #[serde(default)]
246 query: Option<String>,
247 }
248
249 /// Shared by the issue and pull request tools, which draw on one numbering.
250 #[derive(Debug, Deserialize, JsonSchema)]
251 struct NumberArgs {
252 /// The issue or pull request number.
253 number: i64,
254 /// Repository as OWNER/NAME. Defaults to the repository the server is
255 /// running in.
256 #[serde(default)]
257 repo: Option<String>,
258 }
259
260 #[derive(Debug, Deserialize, JsonSchema)]
261 struct CreateIssueArgs {
262 /// Issue title.
263 title: String,
264 /// Issue body, in Markdown.
265 #[serde(default)]
266 body: Option<String>,
267 /// Repository as OWNER/NAME. Defaults to the repository the server is
268 /// running in.
269 #[serde(default)]
270 repo: Option<String>,
271 }
272
273 #[derive(Debug, Deserialize, JsonSchema)]
274 struct AddCommentArgs {
275 /// The issue or pull request number to comment on.
276 number: i64,
277 /// Comment body, in Markdown.
278 body: String,
279 /// Repository as OWNER/NAME. Defaults to the repository the server is
280 /// running in.
281 #[serde(default)]
282 repo: Option<String>,
283 }
284
285 #[tool_router(router = issue_router)]
286 impl SiMcpServer {
287 /// List a repository's issues, optionally filtered by state and a
288 /// title/body substring.
289 #[tool(annotations(read_only_hint = true))]
290 async fn list_issues(
291 &self,
292 Parameters(ListIssuesArgs { repo, state, query }): Parameters<ListIssuesArgs>,
293 ) -> Result<CallToolResult, ErrorData> {
294 let repo = self.repo(repo)?;
295 let issues = self
296 .client()?
297 .issues(&repo, state.into(), query.as_deref())
298 .await
299 .map_err(to_error_data)?;
300 json_result(&issues)
301 }
302
303 /// Fetch one issue by number, including its body and comments.
304 #[tool(annotations(read_only_hint = true))]
305 async fn get_issue(
306 &self,
307 Parameters(NumberArgs { number, repo }): Parameters<NumberArgs>,
308 ) -> Result<CallToolResult, ErrorData> {
309 let repo = self.repo(repo)?;
310 let issue = self
311 .client()?
312 .issue(&repo, number)
313 .await
314 .map_err(to_error_data)?;
315 json_result(&issue)
316 }
317
318 /// Open a new issue.
319 #[tool]
320 async fn create_issue(
321 &self,
322 Parameters(CreateIssueArgs { title, body, repo }): Parameters<CreateIssueArgs>,
323 ) -> Result<CallToolResult, ErrorData> {
324 let repo = self.repo(repo)?;
325 let created = self
326 .client()?
327 .create_issue(&repo, &title, body.as_deref())
328 .await
329 .map_err(to_error_data)?;
330 json_result(&created)
331 }
332
333 /// Comment on an issue or a pull request — they share one numbering.
334 #[tool]
335 async fn add_issue_comment(
336 &self,
337 Parameters(AddCommentArgs { number, body, repo }): Parameters<AddCommentArgs>,
338 ) -> Result<CallToolResult, ErrorData> {
339 let repo = self.repo(repo)?;
340 let comment = self
341 .client()?
342 .add_comment(&repo, number, &body)
343 .await
344 .map_err(to_error_data)?;
345 json_result(&comment)
346 }
347 }
348
349 // --------------------------------------------------------------------- pr --
350
351 #[derive(Debug, Deserialize, JsonSchema)]
352 struct ListPullsArgs {
353 /// Repository as OWNER/NAME. Defaults to the repository the server is
354 /// running in.
355 #[serde(default)]
356 repo: Option<String>,
357 /// Which pull requests to list. Defaults to open.
358 #[serde(default)]
359 state: StateArg,
360 }
361
362 #[derive(Debug, Deserialize, JsonSchema)]
363 struct CreatePullArgs {
364 /// Pull request title.
365 title: String,
366 /// Branch to merge from. Defaults to the branch checked out where the
367 /// server is running.
368 #[serde(default)]
369 head: Option<String>,
370 /// Branch to merge into. Defaults to main.
371 #[serde(default)]
372 base: Option<String>,
373 /// Pull request body, in Markdown.
374 #[serde(default)]
375 body: Option<String>,
376 /// Repository as OWNER/NAME. Defaults to the repository the server is
377 /// running in.
378 #[serde(default)]
379 repo: Option<String>,
380 }
381
382 #[tool_router(router = pr_router)]
383 impl SiMcpServer {
384 /// List a repository's pull requests, optionally filtered by state.
385 #[tool(annotations(read_only_hint = true))]
386 async fn list_pull_requests(
387 &self,
388 Parameters(ListPullsArgs { repo, state }): Parameters<ListPullsArgs>,
389 ) -> Result<CallToolResult, ErrorData> {
390 let repo = self.repo(repo)?;
391 let pulls = self
392 .client()?
393 .pulls(&repo, state.into())
394 .await
395 .map_err(to_error_data)?;
396 json_result(&pulls)
397 }
398
399 /// Fetch one pull request with its comments and unified diff. Diffs past
400 /// 100 kB come back truncated and flagged.
401 #[tool(annotations(read_only_hint = true))]
402 async fn get_pull_request(
403 &self,
404 Parameters(NumberArgs { number, repo }): Parameters<NumberArgs>,
405 ) -> Result<CallToolResult, ErrorData> {
406 let repo = self.repo(repo)?;
407 let pull = self
408 .client()?
409 .pull(&repo, number)
410 .await
411 .map_err(to_error_data)?;
412 json_result(&pull)
413 }
414
415 /// Open a pull request from one branch into another.
416 #[tool]
417 async fn create_pull_request(
418 &self,
419 Parameters(CreatePullArgs {
420 title,
421 head,
422 base,
423 body,
424 repo,
425 }): Parameters<CreatePullArgs>,
426 ) -> Result<CallToolResult, ErrorData> {
427 let repo = self.repo(repo)?;
428 let head = match head {
429 Some(head) => head,
430 None => {
431 let cwd = std::env::current_dir().map_err(to_error_data)?;
432 git::current_branch(&cwd).ok_or_else(|| {
433 ErrorData::invalid_request(
434 "Could not determine the current branch. Pass `head`.",
435 None,
436 )
437 })?
438 }
439 };
440 let base = base.unwrap_or_else(|| "main".to_string());
441
442 let created = self
443 .client()?
444 .create_pull(&repo, &title, &head, &base, body.as_deref())
445 .await
446 .map_err(to_error_data)?;
447 json_result(&created)
448 }
449 }
450
451 // ------------------------------------------------------------------- code --
452
453 #[derive(Debug, Deserialize, JsonSchema)]
454 struct FileContentsArgs {
455 /// Path to the file, relative to the repository root.
456 path: String,
457 /// Branch, tag, or commit SHA. Defaults to the repository's default branch.
458 #[serde(default, rename = "ref")]
459 git_ref: Option<String>,
460 /// Repository as OWNER/NAME. Defaults to the repository the server is
461 /// running in.
462 #[serde(default)]
463 repo: Option<String>,
464 }
465
466 #[derive(Debug, Deserialize, JsonSchema)]
467 struct SearchCodeArgs {
468 /// Fixed string to search for. Case-insensitive, not a regex.
469 query: String,
470 /// Branch, tag, or commit SHA. Defaults to the repository's default branch.
471 #[serde(default, rename = "ref")]
472 git_ref: Option<String>,
473 /// How many matches to return.
474 #[serde(default)]
475 limit: Option<u32>,
476 /// Repository as OWNER/NAME. Defaults to the repository the server is
477 /// running in.
478 #[serde(default)]
479 repo: Option<String>,
480 }
481
482 #[tool_router(router = code_router)]
483 impl SiMcpServer {
484 /// Read a file's contents at a ref.
485 #[tool(annotations(read_only_hint = true))]
486 async fn get_file_contents(
487 &self,
488 Parameters(FileContentsArgs {
489 path,
490 git_ref,
491 repo,
492 }): Parameters<FileContentsArgs>,
493 ) -> Result<CallToolResult, ErrorData> {
494 let repo = self.repo(repo)?;
495 let file = self
496 .client()?
497 .file_contents(&repo, &path, git_ref.as_deref())
498 .await
499 .map_err(to_error_data)?;
500 json_result(&file)
501 }
502
503 /// Search a repository's tracked files for a fixed string, returning
504 /// matching files with line snippets.
505 #[tool(annotations(read_only_hint = true))]
506 async fn search_code(
507 &self,
508 Parameters(SearchCodeArgs {
509 query,
510 git_ref,
511 limit,
512 repo,
513 }): Parameters<SearchCodeArgs>,
514 ) -> Result<CallToolResult, ErrorData> {
515 let repo = self.repo(repo)?;
516 let hits = self
517 .client()?
518 .search_code(&repo, &query, git_ref.as_deref(), limit)
519 .await
520 .map_err(to_error_data)?;
521 json_result(&hits)
522 }
523 }
524
525 // ------------------------------------------------------------------- hook --
526
527 #[derive(Debug, Deserialize, JsonSchema)]
528 struct CreateHookArgs {
529 /// URL sigit.si should POST to.
530 url: String,
531 /// Events to subscribe to. Defaults to push.
532 #[serde(default)]
533 events: Option<Vec<String>>,
534 /// Repository as OWNER/NAME. Defaults to the repository the server is
535 /// running in.
536 #[serde(default)]
537 repo: Option<String>,
538 }
539
540 #[derive(Debug, Deserialize, JsonSchema)]
541 struct DeleteHookArgs {
542 /// The webhook's id.
543 id: i64,
544 /// Repository as OWNER/NAME. Defaults to the repository the server is
545 /// running in.
546 #[serde(default)]
547 repo: Option<String>,
548 }
549
550 #[tool_router(router = hook_router)]
551 impl SiMcpServer {
552 /// List a repository's deploy webhooks.
553 #[tool(annotations(read_only_hint = true))]
554 async fn list_hooks(
555 &self,
556 Parameters(RepoArgs { repo }): Parameters<RepoArgs>,
557 ) -> Result<CallToolResult, ErrorData> {
558 let slug = self.slug(repo)?;
559 let hooks = self
560 .client()?
561 .hooks(&slug.owner, &slug.name)
562 .await
563 .map_err(to_error_data)?;
564 json_result(&hooks)
565 }
566
567 /// Register a webhook. The response carries the signing secret, which is
568 /// shown once and cannot be retrieved again.
569 #[tool]
570 async fn create_hook(
571 &self,
572 Parameters(CreateHookArgs { url, events, repo }): Parameters<CreateHookArgs>,
573 ) -> Result<CallToolResult, ErrorData> {
574 let slug = self.slug(repo)?;
575 let events = events.unwrap_or_else(|| vec!["push".to_string()]);
576 let hook = self
577 .client()?
578 .create_hook(&slug.owner, &slug.name, &url, &events)
579 .await
580 .map_err(to_error_data)?;
581 json_result(&hook)
582 }
583
584 /// Remove a webhook. This cannot be undone.
585 #[tool(annotations(destructive_hint = true))]
586 async fn delete_hook(
587 &self,
588 Parameters(DeleteHookArgs { id, repo }): Parameters<DeleteHookArgs>,
589 ) -> Result<CallToolResult, ErrorData> {
590 let slug = self.slug(repo)?;
591 self.client()?
592 .delete_hook(&slug.owner, &slug.name, id)
593 .await
594 .map_err(to_error_data)?;
595 text_result(format!("Deleted webhook {id} from {slug}."))
596 }
597 }
598
599 // ---------------------------------------------------------------- session --
600
601 #[derive(Debug, Deserialize, JsonSchema)]
602 struct SessionIdArgs {
603 /// The Cloud Session's id.
604 id: i64,
605 }
606
607 #[derive(Debug, Deserialize, JsonSchema)]
608 struct CreateSessionArgs {
609 /// Title for the session.
610 #[serde(default)]
611 title: Option<String>,
612 /// Model the session runs on. Defaults to the account's default.
613 #[serde(default)]
614 model: Option<String>,
615 }
616
617 #[derive(Debug, Deserialize, JsonSchema)]
618 struct UpdateSessionArgs {
619 /// The Cloud Session's id.
620 id: i64,
621 /// New title. Omit to leave unchanged.
622 #[serde(default)]
623 title: Option<String>,
624 /// New model. Omit to leave unchanged.
625 #[serde(default)]
626 model: Option<String>,
627 }
628
629 #[derive(Debug, Deserialize, JsonSchema)]
630 struct AppendMessageArgs {
631 /// The Cloud Session's id.
632 id: i64,
633 /// Who the message is from: user or assistant.
634 role: String,
635 /// The message text.
636 content: String,
637 }
638
639 #[tool_router(router = session_router)]
640 impl SiMcpServer {
641 /// List siGit Code Cloud Sessions, most recently updated first.
642 #[tool(annotations(read_only_hint = true))]
643 async fn list_sessions(&self) -> Result<CallToolResult, ErrorData> {
644 let sessions = self.client()?.sessions().await.map_err(to_error_data)?;
645 json_result(&sessions)
646 }
647
648 /// Fetch one Cloud Session with its full transcript.
649 #[tool(annotations(read_only_hint = true))]
650 async fn get_session(
651 &self,
652 Parameters(SessionIdArgs { id }): Parameters<SessionIdArgs>,
653 ) -> Result<CallToolResult, ErrorData> {
654 let session = self.client()?.session(id).await.map_err(to_error_data)?;
655 json_result(&session)
656 }
657
658 /// Start a new Cloud Session.
659 #[tool]
660 async fn create_session(
661 &self,
662 Parameters(CreateSessionArgs { title, model }): Parameters<CreateSessionArgs>,
663 ) -> Result<CallToolResult, ErrorData> {
664 let session = self
665 .client()?
666 .create_session(title.as_deref(), model.as_deref())
667 .await
668 .map_err(to_error_data)?;
669 json_result(&session)
670 }
671
672 /// Rename a Cloud Session or change the model it runs on.
673 #[tool]
674 async fn update_session(
675 &self,
676 Parameters(UpdateSessionArgs { id, title, model }): Parameters<UpdateSessionArgs>,
677 ) -> Result<CallToolResult, ErrorData> {
678 let session = self
679 .client()?
680 .update_session(id, title.as_deref(), model.as_deref())
681 .await
682 .map_err(to_error_data)?;
683 json_result(&session)
684 }
685
686 /// Append one message to a Cloud Session's transcript.
687 #[tool]
688 async fn append_session_message(
689 &self,
690 Parameters(AppendMessageArgs { id, role, content }): Parameters<AppendMessageArgs>,
691 ) -> Result<CallToolResult, ErrorData> {
692 let appended = self
693 .client()?
694 .append_message(id, &role, &content)
695 .await
696 .map_err(to_error_data)?;
697 json_result(&appended)
698 }
699
700 /// Delete a Cloud Session and its transcript. This cannot be undone.
701 #[tool(annotations(destructive_hint = true))]
702 async fn delete_session(
703 &self,
704 Parameters(SessionIdArgs { id }): Parameters<SessionIdArgs>,
705 ) -> Result<CallToolResult, ErrorData> {
706 self.client()?
707 .delete_session(id)
708 .await
709 .map_err(to_error_data)?;
710 text_result(format!("Deleted session {id}."))
711 }
712 }
713
714 // ---------------------------------------------------------------- billing --
715
716 #[tool_router(router = billing_router)]
717 impl SiMcpServer {
718 /// Show the account's current plan and cloud usage.
719 #[tool(annotations(read_only_hint = true))]
720 async fn get_billing(&self) -> Result<CallToolResult, ErrorData> {
721 let billing = self.client()?.billing().await.map_err(to_error_data)?;
722 json_result(&billing)
723 }
724 }
725
726 #[tool_handler(router = self.tool_router)]
727 impl ServerHandler for SiMcpServer {
728 fn get_info(&self) -> ServerInfo {
729 // `Implementation` is `#[non_exhaustive]`, so start from the build-env
730 // default and override the identity fields to report `si`, not `rmcp`.
731 let mut server_info = Implementation::from_build_env();
732 server_info.name = "si".to_string();
733 server_info.version = env!("CARGO_PKG_VERSION").to_string();
734
735 ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
736 .with_server_info(server_info)
737 .with_instructions(
738 "The sigit.si CLI exposed as MCP tools. Authentication uses the token stored \
739 by `si auth login`; tools run non-interactively. Every repository tool takes \
740 `repo` as OWNER/NAME, and omitting it falls back to the sigit.si repository \
741 the server was started in — call `current_repository` to see what that \
742 resolves to. Use `list_repositories` to find the OWNER/NAME of anything else.",
743 )
744 }
745 }
746
747 impl SiMcpServer {
748 /// [`Self::repo`], parsed back into its owner and name halves for the REST
749 /// endpoints that take them separately.
750 fn slug(&self, explicit: Option<String>) -> Result<RepoSlug, ErrorData> {
751 self.ctx
752 .resolve_repo(explicit)
753 .map_err(|e| ErrorData::invalid_request(e.to_string(), None))
754 }
755 }
756
757 /// Assemble the router from the requested toolsets, then drop the writers if
758 /// `--read-only` was passed.
759 ///
760 /// An unknown toolset name is an error rather than a silent no-op: a typo in an
761 /// editor's config would otherwise show up as a server that mysteriously
762 /// offers fewer tools than expected.
763 fn build_router(toolsets: &[String], read_only: bool) -> Result<ToolRouter<SiMcpServer>> {
764 let selected: Vec<String> = if toolsets.is_empty() {
765 TOOLSETS.iter().map(|name| name.to_string()).collect()
766 } else {
767 toolsets
768 .iter()
769 .map(|name| name.trim().to_ascii_lowercase())
770 .collect()
771 };
772
773 let mut router = ToolRouter::new();
774 for name in &selected {
775 let group = match name.as_str() {
776 "account" => SiMcpServer::account_router(),
777 "repo" => SiMcpServer::repo_router(),
778 "issue" => SiMcpServer::issue_router(),
779 "pr" => SiMcpServer::pr_router(),
780 "code" => SiMcpServer::code_router(),
781 "hook" => SiMcpServer::hook_router(),
782 "session" => SiMcpServer::session_router(),
783 "billing" => SiMcpServer::billing_router(),
784 other => {
785 return Err(anyhow!(
786 "Unknown toolset {other:?}. Expected one of: {}.",
787 TOOLSETS.join(", ")
788 ))
789 }
790 };
791 router.merge(group);
792 }
793
794 if read_only {
795 let writers: Vec<String> = router
796 .list_all()
797 .into_iter()
798 .filter(|tool| {
799 tool.annotations
800 .as_ref()
801 .and_then(|annotations| annotations.read_only_hint)
802 != Some(true)
803 })
804 .map(|tool| tool.name.to_string())
805 .collect();
806
807 for name in writers {
808 router.remove_route(&name);
809 }
810 }
811
812 Ok(router)
813 }
814
815 /// Run the MCP server over stdio until the client disconnects.
816 pub async fn run(ctx: Ctx, args: McpArgs) -> Result<()> {
817 let router = build_router(&args.toolsets, args.read_only)?;
818 tracing::info!(tools = router.list_all().len(), "starting the MCP server");
819
820 let running = SiMcpServer::new(ctx, router)
821 .serve(stdio())
822 .await
823 .map_err(|e| anyhow!("Could not start the MCP server: {e}"))?;
824
825 running
826 .waiting()
827 .await
828 .map_err(|e| anyhow!("The MCP server stopped unexpectedly: {e}"))?;
829 Ok(())
830 }
831
832 #[cfg(test)]
833 mod tests {
834 use super::*;
835
836 fn tool_names(toolsets: &[String], read_only: bool) -> Vec<String> {
837 build_router(toolsets, read_only)
838 .unwrap()
839 .list_all()
840 .into_iter()
841 .map(|tool| tool.name.to_string())
842 .collect()
843 }
844
845 #[test]
846 fn the_default_router_spans_every_toolset() {
847 let names = tool_names(&[], false);
848
849 for expected in [
850 "whoami",
851 "list_repositories",
852 "list_issues",
853 "list_pull_requests",
854 "search_code",
855 "list_hooks",
856 "list_sessions",
857 "get_billing",
858 ] {
859 assert!(
860 names.contains(&expected.to_string()),
861 "missing {expected:?}"
862 );
863 }
864 }
865
866 #[test]
867 fn a_toolset_selection_leaves_the_rest_out() {
868 let names = tool_names(&["issue".to_string(), "pr".to_string()], false);
869
870 assert!(names.contains(&"create_issue".to_string()));
871 assert!(names.contains(&"get_pull_request".to_string()));
872 assert!(!names.contains(&"get_billing".to_string()));
873 assert!(!names.contains(&"list_sessions".to_string()));
874 }
875
876 #[test]
877 fn read_only_mode_drops_every_writer() {
878 let names = tool_names(&[], true);
879
880 assert!(names.contains(&"list_issues".to_string()));
881 assert!(names.contains(&"get_file_contents".to_string()));
882
883 for writer in [
884 "create_issue",
885 "create_pull_request",
886 "add_issue_comment",
887 "create_repository",
888 "create_hook",
889 "delete_hook",
890 "create_session",
891 "delete_session",
892 ] {
893 assert!(
894 !names.contains(&writer.to_string()),
895 "read-only mode should have dropped {writer:?}"
896 );
897 }
898 }
899
900 #[test]
901 fn an_unknown_toolset_is_rejected() {
902 let error = build_router(&["repo".to_string(), "nope".to_string()], false).unwrap_err();
903 assert!(error.to_string().contains("nope"));
904 }
905
906 #[test]
907 fn toolset_names_are_case_and_space_insensitive() {
908 assert_eq!(
909 tool_names(&[" Billing ".to_string()], false),
910 vec!["get_billing".to_string()]
911 );
912 }
913 }