1#![allow(dead_code)]
33
34use std::sync::{Arc, Mutex};
35
36use rmcp::handler::server::router::prompt::{PromptRoute, PromptRouter};
37use rmcp::handler::server::router::tool::ToolRouter;
38use rmcp::handler::server::wrapper::Parameters;
39use rmcp::model::*;
40use rmcp::{tool, tool_handler, tool_router, ErrorData as McpError, ServerHandler};
41use serde::{Deserialize, Serialize};
42
43use crate::server::manifest::Manifest;
44use crate::server::skills::ResolvedRegistry;
45use crate::server::source::{
46 self, resolve_dir_under_roots, GrepOpts, ListOpts, ReadOpts, SourceRootsProvider,
47};
48
49pub type RepoProvider = Arc<dyn Fn() -> Option<String> + Send + Sync>;
53
54pub struct ResultCtx {
59 pub source_roots: Vec<String>,
61 pub active_repo: Option<String>,
64}
65
66pub type ResultPostprocessHook =
80 Arc<dyn Fn(&str, &serde_json::Value, &str, &ResultCtx) -> Option<String> + Send + Sync>;
81
82fn append_footer(body: String, footer: Option<String>) -> String {
86 match footer {
87 Some(f) if !f.is_empty() => format!("{body}\n\n{f}"),
88 _ => body,
89 }
90}
91
92#[derive(Clone, Default)]
94pub struct ServerOptions {
95 pub name: Option<String>,
97 pub instructions: Option<String>,
99 pub source_roots: Option<SourceRootsProvider>,
102 pub default_repo: Option<RepoProvider>,
105 pub workspace: Option<crate::server::workspace::Workspace>,
107 pub builtins: crate::server::manifest::BuiltinsConfig,
112 pub extensions: serde_json::Map<String, serde_json::Value>,
117 pub result_postprocess: Option<ResultPostprocessHook>,
121}
122
123impl std::fmt::Debug for ServerOptions {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 f.debug_struct("ServerOptions")
126 .field("name", &self.name)
127 .field("instructions", &self.instructions)
128 .field(
129 "source_roots",
130 &self.source_roots.as_ref().map(|_| "<provider>"),
131 )
132 .field(
133 "default_repo",
134 &self.default_repo.as_ref().map(|_| "<provider>"),
135 )
136 .finish()
137 }
138}
139
140impl ServerOptions {
141 pub fn from_manifest(manifest: Option<&Manifest>, fallback_name: &str) -> Self {
142 Self {
143 name: manifest
144 .and_then(|m| m.name.clone())
145 .or_else(|| Some(fallback_name.to_string())),
146 instructions: manifest.and_then(|m| m.instructions.clone()),
147 source_roots: None,
148 default_repo: None,
149 workspace: None,
150 builtins: manifest.map(|m| m.builtins.clone()).unwrap_or_default(),
151 extensions: manifest.map(|m| m.extensions.clone()).unwrap_or_default(),
152 result_postprocess: None,
153 }
154 }
155
156 pub fn with_static_source_roots(mut self, roots: Vec<String>) -> Self {
157 let captured = Arc::new(roots);
158 self.source_roots = Some(Arc::new(move || captured.as_ref().clone()));
159 self
160 }
161
162 pub fn with_dynamic_source_roots(mut self, provider: SourceRootsProvider) -> Self {
163 self.source_roots = Some(provider);
164 self
165 }
166
167 pub fn with_static_repo(mut self, repo: String) -> Self {
168 self.default_repo = Some(Arc::new(move || Some(repo.clone())));
169 self
170 }
171
172 pub fn with_dynamic_repo(mut self, provider: RepoProvider) -> Self {
173 self.default_repo = Some(provider);
174 self
175 }
176
177 pub fn with_workspace(mut self, ws: crate::server::workspace::Workspace) -> Self {
182 let ws_for_roots = ws.clone();
183 let ws_for_repo = ws.clone();
184 self.workspace = Some(ws);
185 self.source_roots = Some(Arc::new(move || {
186 ws_for_roots
187 .active_repo_path()
188 .map(|p| vec![p.to_string_lossy().into_owned()])
189 .unwrap_or_default()
190 }));
191 self.default_repo = Some(Arc::new(move || ws_for_repo.default_github_repo()));
192 self
193 }
194
195 pub fn with_result_postprocess(mut self, hook: ResultPostprocessHook) -> Self {
200 self.result_postprocess = Some(hook);
201 self
202 }
203}
204
205#[derive(Debug, Deserialize, Serialize, schemars::JsonSchema)]
206pub struct PingArgs {
207 #[serde(default, skip_serializing_if = "Option::is_none")]
209 pub message: Option<String>,
210}
211
212#[derive(Debug, Deserialize, Serialize, schemars::JsonSchema)]
213pub struct ReadSourceArgs {
214 pub file_path: String,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub start_line: Option<usize>,
219 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub end_line: Option<usize>,
222 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub grep: Option<String>,
225 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub grep_context: Option<usize>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
230 pub max_matches: Option<usize>,
231 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub max_chars: Option<usize>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
240 pub rev: Option<String>,
241}
242
243#[derive(Debug, Deserialize, Serialize, schemars::JsonSchema)]
244pub struct GrepArgs {
245 pub pattern: String,
247 #[serde(default, skip_serializing_if = "Option::is_none")]
249 pub glob: Option<String>,
250 #[serde(default)]
252 pub context: usize,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub max_results: Option<usize>,
256 #[serde(default)]
258 pub case_insensitive: bool,
259}
260
261#[derive(Debug, Default, Deserialize, Serialize, schemars::JsonSchema)]
262pub struct SetRootDirArgs {
263 pub path: String,
265 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub revs: Option<crate::server::workspace::RevsRequest>,
274}
275
276#[derive(Debug, Default, Deserialize, Serialize, schemars::JsonSchema)]
277pub struct RepoManagementArgs {
278 #[serde(default, skip_serializing_if = "Option::is_none")]
280 pub name: Option<String>,
281 #[serde(default)]
283 pub delete: bool,
284 #[serde(default)]
286 pub update: bool,
287 #[serde(default)]
291 pub force_rebuild: bool,
292 #[serde(default, skip_serializing_if = "Option::is_none")]
300 pub revs: Option<crate::server::workspace::RevsRequest>,
301}
302
303#[derive(Debug, Deserialize, Serialize, schemars::JsonSchema)]
304pub struct GithubIssuesArgs {
305 #[serde(default, skip_serializing_if = "Option::is_none")]
307 pub number: Option<u64>,
308 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub repo_name: Option<String>,
311 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub query: Option<String>,
314 #[serde(default = "default_kind")]
316 pub kind: String,
317 #[serde(default = "default_state")]
319 pub state: String,
320 #[serde(default, skip_serializing_if = "Option::is_none")]
322 pub sort: Option<String>,
323 #[serde(default = "default_limit")]
325 pub limit: usize,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub labels: Option<String>,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub element_id: Option<String>,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
339 pub lines: Option<String>,
340 #[serde(default, skip_serializing_if = "Option::is_none")]
343 pub grep: Option<String>,
344 #[serde(default, skip_serializing_if = "Option::is_none")]
347 pub context: Option<usize>,
348 #[serde(default)]
351 pub refresh: bool,
352}
353
354fn default_kind() -> String {
355 "all".to_string()
356}
357fn default_state() -> String {
358 "open".to_string()
359}
360fn default_limit() -> usize {
361 20
362}
363
364impl Default for GithubIssuesArgs {
365 fn default() -> Self {
366 Self {
367 number: None,
368 repo_name: None,
369 query: None,
370 kind: default_kind(),
371 state: default_state(),
372 sort: None,
373 limit: default_limit(),
374 labels: None,
375 element_id: None,
376 lines: None,
377 grep: None,
378 context: None,
379 refresh: false,
380 }
381 }
382}
383
384#[derive(Debug, Default, Deserialize, Serialize, schemars::JsonSchema)]
385pub struct GithubApiArgs {
386 pub path: String,
393 #[serde(default, skip_serializing_if = "Option::is_none")]
395 pub repo_name: Option<String>,
396 #[serde(default, skip_serializing_if = "Option::is_none")]
398 pub truncate_at: Option<usize>,
399}
400
401#[derive(Debug, Deserialize, Serialize, schemars::JsonSchema)]
402pub struct ListSourceArgs {
403 #[serde(default = "default_path")]
405 pub path: String,
406 #[serde(default = "default_depth")]
408 pub depth: usize,
409 #[serde(default, skip_serializing_if = "Option::is_none")]
411 pub glob: Option<String>,
412 #[serde(default)]
414 pub dirs_only: bool,
415}
416
417fn default_path() -> String {
418 ".".to_string()
419}
420fn default_depth() -> usize {
421 1
422}
423
424#[derive(Debug, Default, Deserialize, Serialize, schemars::JsonSchema)]
425pub struct ScreenStargazersArgs {
426 #[serde(default, skip_serializing_if = "Option::is_none")]
428 pub repo: Option<String>,
429 #[serde(default, skip_serializing_if = "Option::is_none")]
432 pub users: Option<String>,
433 #[serde(default, skip_serializing_if = "Option::is_none")]
437 pub preset: Option<String>,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
440 pub rank_by: Option<String>,
441 #[serde(default, skip_serializing_if = "Option::is_none")]
443 pub top: Option<usize>,
444 #[serde(default, skip_serializing_if = "Option::is_none")]
446 pub min_keywords: Option<usize>,
447 #[serde(default, skip_serializing_if = "Option::is_none")]
449 pub active_since: Option<String>,
450 #[serde(default)]
452 pub adopters_only: bool,
453 #[serde(default)]
455 pub stack_only: bool,
456 #[serde(default, skip_serializing_if = "Option::is_none")]
461 pub keywords: Option<String>,
462 #[serde(default, skip_serializing_if = "Option::is_none")]
466 pub stack: Option<String>,
467 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub max_stargazers: Option<usize>,
470 #[serde(default, skip_serializing_if = "Option::is_none")]
474 pub element_id: Option<String>,
475 #[serde(default)]
477 pub refresh: bool,
478}
479
480#[derive(Clone)]
485pub struct McpServer {
486 options: ServerOptions,
487 tool_router: ToolRouter<McpServer>,
488 prompt_router: PromptRouter<McpServer>,
493}
494
495#[tool_router]
496impl McpServer {
497 pub fn new(options: ServerOptions) -> Self {
498 let mut server = Self {
499 options,
500 tool_router: Self::tool_router(),
501 prompt_router: PromptRouter::new(),
502 };
503 server.register_github_tools_if_authorized();
504 server.register_local_workspace_tools();
505 server.gate_workspace_tools();
506 server
507 }
508
509 fn gate_workspace_tools(&mut self) {
517 if self.options.workspace.is_none() {
518 self.tool_router.remove_route("repo_management");
519 }
520 }
521
522 fn register_local_workspace_tools(&mut self) {
526 let Some(ws) = self.options.workspace.clone() else {
527 return;
528 };
529 if !matches!(ws.kind(), crate::server::workspace::WorkspaceKind::Local) {
530 return;
531 }
532 self.register_typed_tool::<SetRootDirArgs, _>(
533 "set_root_dir",
534 "Swap the active source root (local-workspace mode only). Pass `path` \
535 to a directory; the framework canonicalises it, rebinds the source \
536 tools (`read_source`, `grep`, `list_source`), and fires the post-\
537 activate hook so any downstream graph rebuilds against the new root. \
538 Pass `revs` (an integer N, or a list of git revspecs) to load multiple \
539 revisions of the root into one graph — N loads the newest N stable \
540 release tags of the dominant tag family plus HEAD (prereleases and \
541 unrelated tag families skipped); requires the root to be a git repo. \
542 Inventory persists across swaps; SHA-gating skips rebuilds when \
543 the same root is re-bound with no content changes.",
544 move |args: SetRootDirArgs| {
545 let p = std::path::PathBuf::from(&args.path);
546 ws.set_root_dir(&p, args.revs.as_ref())
547 },
548 );
549 }
550
551 fn register_github_tools_if_authorized(&mut self) {
557 if !crate::github::has_git_token() {
558 tracing::info!(
559 "GITHUB_TOKEN not set — github_issues / github_api tools hidden from the agent. \
560 Set the env var and restart to enable them."
561 );
562 return;
563 }
564 let default_repo = self.options.default_repo.clone();
565 let repo_provider = default_repo.clone();
566 let cache: Arc<Mutex<crate::cache::ElementCache>> =
572 Arc::new(Mutex::new(crate::cache::ElementCache::new()));
573 let cache_for_issues = cache.clone();
574 self.register_typed_tool::<GithubIssuesArgs, _>(
575 "github_issues",
576 "Search, list, or fetch GitHub issues / pull requests / Discussions. \
577 Pass `number=N` for FETCH (single issue/PR/discussion); `query=\"...\"` \
578 for SEARCH (across issues+PRs and Discussions); neither for LIST. \
579 `kind` ∈ \"issue\" / \"pr\" / \"discussion\" / \"all\" (default). \
580 `state` ∈ \"open\" (default) / \"closed\" / \"all\". `limit` caps \
581 result count (default 20). `labels` is a comma-separated string. \
582 `repo_name=\"org/repo\"` overrides the active repo for one call. \
583 FETCH responses collapse big code blocks / patches / comments into \
584 `cb_N` / `patch_N` / `comment_N` / `overflow` placeholders; pass \
585 `element_id=\"cb_1\"` (with the same `number`) to retrieve a single \
586 element, optionally narrowed by `lines=\"40-60\"` or `grep=\"pat\"`. \
587 `refresh=true` bypasses the cache for re-fetch.",
588 move |args: GithubIssuesArgs| {
589 let repo = match resolve_repo_from(repo_provider.as_ref(), args.repo_name.clone()) {
590 Ok(r) => r,
591 Err(msg) => return msg,
592 };
593 if let Some(number) = args.number {
599 let context = args.context.unwrap_or(3);
600 let mut guard = cache_for_issues.lock().unwrap();
601 return guard.fetch_issue(
602 &repo,
603 number,
604 args.element_id.as_deref(),
605 args.lines.as_deref(),
606 args.grep.as_deref(),
607 context,
608 args.refresh,
609 );
610 }
611 if args.element_id.is_some() {
612 return "element_id requires `number=N` (the issue/PR being drilled into)."
613 .to_string();
614 }
615 crate::github::github_issues_rust(
617 Some(&repo),
618 args.number,
619 args.query.as_deref(),
620 &args.kind,
621 &args.state,
622 args.sort.as_deref(),
623 args.limit,
624 args.labels.as_deref(),
625 )
626 },
627 );
628 let repo_provider = default_repo.clone();
629 let repo_for_screen = default_repo;
630 self.register_typed_tool::<GithubApiArgs, _>(
631 "github_api",
632 "Read-only GET against the GitHub REST API. `path` may be a \
633 repo-relative endpoint (\"pulls?state=open\", \"commits/abc123\", \
634 \"branches\", \"compare/main...feature\") which is auto-prefixed \
635 with /repos/<repo_name>/, or a top-level resource (\"search/issues?q=...\", \
636 \"users/octocat\", \"repos/owner/name\") which passes through. A \
637 leading slash is optional and accepted on either form. Returns \
638 JSON, truncated at 80 KB by default.",
639 move |args: GithubApiArgs| match resolve_repo_from(
640 repo_provider.as_ref(),
641 args.repo_name.clone(),
642 ) {
643 Ok(repo) => {
644 let truncate_at = args.truncate_at.unwrap_or(80_000);
645 crate::github::git_api_internal(&repo, &args.path, truncate_at)
646 }
647 Err(msg) => msg,
648 },
649 );
650
651 if self.options.builtins.screen_stargazers {
659 let screen_store: Arc<Mutex<crate::screen::ScreenStore>> =
660 Arc::new(Mutex::new(crate::screen::ScreenStore::new()));
661 self.register_typed_tool::<ScreenStargazersArgs, _>(
662 "screen_stargazers",
663 "Screen the people around a GitHub project to find relevant developers, \
664 notable/legendary devs, architectural peers, and actual users — cheaply. \
665 Seed on a repo (`repo=\"owner/repo\"` → screens its stargazers) OR an \
666 explicit user list (`users=\"alice,bob\"` → screens them directly). With \
667 just a repo it auto-derives relevance keywords + tech stack from the repo \
668 itself, bulk-fetches each person's public repo portfolio over plain REST \
669 (~1 request per person, no GraphQL, no READMEs), classifies them, and \
670 enriches a bounded shortlist with follower counts, dependency-adoption, \
671 stack co-location, and contributions. Every person gets a normalized \
672 0–100 score vector on four axes — relatedness, popularity, effort, \
673 recency. RANK/FILTER: pass a `preset` (\"outreach\"=relevant+active by \
674 reach, \"peers\"=your stack by effort, \"legends\"=biggest reach any \
675 domain, \"intel\"=on-domain by popularity, \"adopters\"=actual users), or \
676 `rank_by`=relatedness|popularity|effort|recency with filters \
677 (`min_keywords`, `active_since`, `adopters_only`, `stack_only`) and \
678 `top`=N (rank-then-take-N, default 10) for a focused filter→rank→take \
679 view; with none, the full multi-lens browse: \
680 `✅ ADOPTERS` (stargazers whose repos actually declare your package as a \
681 dependency — real users, not just watchers), `★ MOST RELEVANT` \
682 (relatedness — repos matching your topic keywords, with follower counts \
683 and external contributions), `🏆 NOTABLE` (popularity/reach lens — your \
684 highest-traction stargazers, flagged `LEGEND` for big audiences/projects), \
685 `✦ QUALITY` (best-kept maintained projects), `⚙ STACK MATCH` (architectural \
686 peers who build in your stack — co-location-confirmed where possible), and \
687 a cohort inventory. Override the auto-config with `keywords=\"graph,rag,agent\"` \
688 (single words — \"knowledge,graph\" not \"knowledge-graph\") and \
689 `stack=\"Rust,Python\"`; re-calling with new values re-ranks the cached \
690 fetch for free. Treat description-based leads as candidates to verify by \
691 drilling. DRILL via `element_id`: `\"cohort:<key>\"` (established / single / \
692 prolific / casual / dormant / consumers — the overview lists each key), \
693 `\"user:<login>\"` (portfolio), `\"user:<login>/repo:<name>\"` (repo profile), \
694 or `\"user:<login>/repo:<name>/readme\"` (README gist — the only drill that \
695 costs a request). `max_stargazers` samples the most-recent N (the overview \
696 reports if results are partial); `refresh=true` re-fetches.",
697 move |args: ScreenStargazersArgs| {
698 use crate::screen::{self, Filters, RankBy, Seed, Selection};
699 let split_csv = |s: Option<String>| -> Vec<String> {
700 s.map(|v| {
701 v.split(',')
702 .map(|t| t.trim().to_string())
703 .filter(|t| !t.is_empty())
704 .collect()
705 })
706 .unwrap_or_default()
707 };
708 let seed = if let Some(u) = &args.users {
710 Seed::Users(split_csv(Some(u.clone())))
711 } else {
712 let repo =
713 match resolve_repo_from(repo_for_screen.as_ref(), args.repo.clone()) {
714 Ok(r) => r,
715 Err(msg) => return msg,
716 };
717 if let Some(err) = crate::git_refs::validate_repo(&repo) {
718 return err;
719 }
720 Seed::Repo(repo)
721 };
722 let cfg = screen::ScreenConfig {
723 max_stargazers: args.max_stargazers,
724 max_repos_per_user: 100,
725 relevance_keywords: split_csv(args.keywords)
726 .into_iter()
727 .map(|k| k.to_lowercase())
728 .collect(),
729 stack_languages: split_csv(args.stack),
730 };
731 let top = args.top.unwrap_or(10);
733 let filters = Filters {
734 min_keywords: args.min_keywords,
735 active_since: args.active_since.clone(),
736 adopters_only: args.adopters_only,
737 stack_only: args.stack_only,
738 ..Default::default()
739 };
740 let filters_active = filters.min_keywords.is_some()
741 || filters.active_since.is_some()
742 || filters.adopters_only
743 || filters.stack_only;
744 let selection: Option<Selection> = if let Some(name) = &args.preset {
745 screen::preset(name, top)
746 } else if args.rank_by.is_some() || filters_active {
747 Some(Selection {
748 filters,
749 rank: args
750 .rank_by
751 .as_deref()
752 .and_then(RankBy::parse)
753 .unwrap_or(RankBy::Relatedness),
754 label: "SELECTION".into(),
755 take: top,
756 })
757 } else {
758 None
759 };
760 screen::screen_dispatch(
761 &screen_store,
762 &seed,
763 &cfg,
764 selection.as_ref(),
765 args.element_id.as_deref(),
766 args.refresh,
767 )
768 },
769 );
770 }
771 }
772
773 pub fn builtins(&self) -> &crate::server::manifest::BuiltinsConfig {
780 &self.options.builtins
781 }
782
783 pub fn tool_router_mut(&mut self) -> &mut ToolRouter<McpServer> {
789 &mut self.tool_router
790 }
791
792 pub fn prompt_router_mut(&mut self) -> &mut PromptRouter<McpServer> {
797 &mut self.prompt_router
798 }
799
800 pub fn register_typed_tool<T, F>(
815 &mut self,
816 name: &'static str,
817 description: &'static str,
818 handler: F,
819 ) where
820 T: for<'de> serde::Deserialize<'de>
821 + schemars::JsonSchema
822 + Default
823 + Send
824 + Sync
825 + 'static,
826 F: Fn(T) -> String + Send + Sync + 'static,
827 {
828 use std::pin::Pin;
829 type DynFut<'a, R> = Pin<Box<dyn std::future::Future<Output = R> + Send + 'a>>;
830
831 let schema_obj = serde_json::to_value(schemars::schema_for!(T))
832 .ok()
833 .and_then(|v| v.as_object().cloned())
834 .unwrap_or_default();
835 let attr = rmcp::model::Tool::new(name, description, Arc::new(schema_obj));
836 let handler = std::sync::Arc::new(handler);
837 let tool_name = name;
842 let postprocess = self.options.result_postprocess.clone();
843 let source_roots = self.options.source_roots.clone();
844 let workspace = self.options.workspace.clone();
845
846 self.tool_router
847 .add_route(rmcp::handler::server::router::tool::ToolRoute::new_dyn(
848 attr,
849 move |ctx: rmcp::handler::server::tool::ToolCallContext<'_, McpServer>|
850 -> DynFut<'_, Result<rmcp::model::CallToolResult, rmcp::ErrorData>> {
851 let handler = handler.clone();
852 let arguments = ctx.arguments.clone();
853 let postprocess = postprocess.clone();
854 let source_roots = source_roots.clone();
855 let workspace = workspace.clone();
856 Box::pin(async move {
857 let args_json = match &arguments {
860 Some(map) => serde_json::Value::Object(map.clone()),
861 None => serde_json::Value::Null,
862 };
863 let args: T = match arguments {
864 Some(map) => {
865 match serde_json::from_value(serde_json::Value::Object(map)) {
866 Ok(a) => a,
867 Err(e) => {
868 return Ok(rmcp::model::CallToolResult::success(vec![
869 rmcp::model::Content::text(format!(
870 "invalid arguments: {e}"
871 )),
872 ]));
873 }
874 }
875 }
876 None => T::default(),
877 };
878 let body = handler(args);
879 let body = match &postprocess {
880 Some(hook) => {
881 let ctx = ResultCtx {
882 source_roots: source_roots
883 .as_ref()
884 .map(|p| p())
885 .unwrap_or_default(),
886 active_repo: workspace
887 .as_ref()
888 .and_then(|w| w.active_repo_name()),
889 };
890 let footer = hook(tool_name, &args_json, &body, &ctx);
891 append_footer(body, footer)
892 }
893 None => body,
894 };
895 Ok(rmcp::model::CallToolResult::success(vec![
896 rmcp::model::Content::text(body),
897 ]))
898 })
899 },
900 ));
901 }
902
903 fn current_source_roots(&self) -> Vec<String> {
904 match &self.options.source_roots {
905 Some(provider) => provider(),
906 None => Vec::new(),
907 }
908 }
909
910 fn finish(&self, tool: &str, args: &serde_json::Value, body: String) -> String {
917 let Some(hook) = &self.options.result_postprocess else {
918 return body;
919 };
920 let ctx = ResultCtx {
921 source_roots: self.current_source_roots(),
922 active_repo: self
923 .options
924 .workspace
925 .as_ref()
926 .and_then(|w| w.active_repo_name()),
927 };
928 let footer = hook(tool, args, &body, &ctx);
929 append_footer(body, footer)
930 }
931
932 #[allow(dead_code)]
937 fn resolve_repo(&self, override_repo: Option<String>) -> Result<String, String> {
938 resolve_repo_from(self.options.default_repo.as_ref(), override_repo)
939 }
940
941 #[tool(
942 description = "Liveness probe — returns 'pong' (or echoes `message` if supplied). \
943 Use to confirm the server framework is wired correctly before \
944 relying on graph- or source-aware tools."
945 )]
946 async fn ping(
947 &self,
948 Parameters(args): Parameters<PingArgs>,
949 ) -> Result<CallToolResult, McpError> {
950 let args_json = serde_json::to_value(&args).unwrap_or(serde_json::Value::Null);
951 let body = args.message.unwrap_or_else(|| "pong".to_string());
952 let body = self.finish("ping", &args_json, body);
953 Ok(CallToolResult::success(vec![Content::text(body)]))
954 }
955
956 #[tool(description = "Read a file from the configured source root(s). Pass \
957 `start_line`/`end_line` to slice, `grep` to filter to matching \
958 lines, `max_chars` to cap output. Pass `rev` (a tag, branch, or \
959 commit SHA) to read the file's content at that git revision via \
960 `git show` instead of the working tree — useful for comparing a \
961 file across releases (requires a git repo source root). Path \
962 traversal attempts are rejected. Available only when source roots \
963 are configured.")]
964 async fn read_source(
965 &self,
966 Parameters(args): Parameters<ReadSourceArgs>,
967 ) -> Result<CallToolResult, McpError> {
968 let roots = self.current_source_roots();
969 if roots.is_empty() {
970 return Ok(CallToolResult::success(vec![Content::text(
971 "Cannot read source: no active source root. Configure source_root in your manifest \
972 or activate one (e.g. via repo_management in workspace mode).",
973 )]));
974 }
975 let args_json = serde_json::to_value(&args).unwrap_or(serde_json::Value::Null);
976 let opts = ReadOpts {
977 start_line: args.start_line,
978 end_line: args.end_line,
979 grep: args.grep,
980 grep_context: args.grep_context,
981 max_matches: args.max_matches,
982 max_chars: args.max_chars,
983 rev: args.rev,
984 };
985 let body = source::read_source(&args.file_path, &roots, &opts);
986 let body = self.finish("read_source", &args_json, body);
987 Ok(CallToolResult::success(vec![Content::text(body)]))
988 }
989
990 #[tool(
991 description = "Search source files using ripgrep. `pattern` is a regex (Rust \
992 syntax). `glob` filters file paths (e.g. \"*.py\"). `context` adds \
993 N surrounding lines per match. Set `case_insensitive=true` for \
994 case-insensitive matching. `max_results` caps total matches \
995 (default 50)."
996 )]
997 async fn grep(
998 &self,
999 Parameters(args): Parameters<GrepArgs>,
1000 ) -> Result<CallToolResult, McpError> {
1001 let roots = self.current_source_roots();
1002 if roots.is_empty() {
1003 return Ok(CallToolResult::success(vec![Content::text(
1004 "Cannot grep: no active source root. Configure source_root in your manifest \
1005 or activate one (e.g. via repo_management in workspace mode).",
1006 )]));
1007 }
1008 let args_json = serde_json::to_value(&args).unwrap_or(serde_json::Value::Null);
1009 let opts = GrepOpts {
1010 glob: args.glob,
1011 context: args.context,
1012 max_results: Some(args.max_results.unwrap_or(50)),
1013 case_insensitive: args.case_insensitive,
1014 };
1015 let body = source::grep(&roots, &args.pattern, &opts);
1016 let body = self.finish("grep", &args_json, body);
1017 Ok(CallToolResult::success(vec![Content::text(body)]))
1018 }
1019
1020 #[tool(
1021 description = "List directory contents under the configured source root. `path` \
1022 is resolved against the first source root (\".\" lists the root \
1023 itself). `depth` controls recursion (1 = flat ls, 2+ = tree). \
1024 `glob` filters entry names. `dirs_only=true` shows only \
1025 directories."
1026 )]
1027 async fn list_source(
1028 &self,
1029 Parameters(args): Parameters<ListSourceArgs>,
1030 ) -> Result<CallToolResult, McpError> {
1031 let roots = self.current_source_roots();
1032 if roots.is_empty() {
1033 return Ok(CallToolResult::success(vec![Content::text(
1034 "Cannot list source: no active source root. Configure source_root in your \
1035 manifest or activate one (e.g. via repo_management in workspace mode).",
1036 )]));
1037 }
1038 let primary = std::path::PathBuf::from(&roots[0]);
1039 let target = match resolve_dir_under_roots(&args.path, &roots) {
1040 Some(p) => p,
1041 None => {
1042 return Ok(CallToolResult::success(vec![Content::text(format!(
1043 "Error: path '{}' resolves outside the configured source roots.",
1044 args.path
1045 ))]));
1046 }
1047 };
1048 let args_json = serde_json::to_value(&args).unwrap_or(serde_json::Value::Null);
1049 let opts = ListOpts {
1050 depth: args.depth,
1051 glob: args.glob,
1052 dirs_only: args.dirs_only,
1053 };
1054 let body = source::list_source(&target, &primary, &opts);
1055 let body = self.finish("list_source", &args_json, body);
1056 Ok(CallToolResult::success(vec![Content::text(body)]))
1057 }
1058
1059 #[tool(
1060 description = "Manage GitHub repos in the workspace. Pass `name='org/repo'` to \
1061 clone (if missing) and activate it as the source root for \
1062 read_source / grep / list_source. Pass `delete=true` to remove a \
1063 repo. Pass `update=true` to fetch upstream changes for the active \
1064 repo (rebuild auto-skipped when HEAD hasn't moved since the last \
1065 build; set `force_rebuild=true` to bypass). Pass `revs` (an \
1066 integer N, or a list of git revspecs) to load multiple revisions \
1067 of the repo into one graph — N loads the newest N stable release \
1068 tags of the dominant tag family plus HEAD (prereleases and \
1069 unrelated tag families skipped); a revs request always rebuilds. \
1070 Call with no \
1071 arguments to list all known repos with their last-access counts. \
1072 Idle repos auto-sweep on each call (default 7 days, configurable \
1073 via --stale-after-days)."
1074 )]
1075 async fn repo_management(
1076 &self,
1077 Parameters(args): Parameters<RepoManagementArgs>,
1078 ) -> Result<CallToolResult, McpError> {
1079 let args_json = serde_json::to_value(&args).unwrap_or(serde_json::Value::Null);
1080 let body = match &self.options.workspace {
1081 Some(ws) => ws.repo_management(
1082 args.name.as_deref(),
1083 args.delete,
1084 args.update,
1085 args.force_rebuild,
1086 args.revs.as_ref(),
1087 ),
1088 None => "repo_management requires --workspace mode.".to_string(),
1089 };
1090 let body = self.finish("repo_management", &args_json, body);
1091 Ok(CallToolResult::success(vec![Content::text(body)]))
1092 }
1093}
1094
1095fn resolve_repo_from(
1103 default_repo: Option<&RepoProvider>,
1104 override_repo: Option<String>,
1105) -> Result<String, String> {
1106 if let Some(r) = override_repo {
1107 if let Some(err) = crate::git_refs::validate_repo(&r) {
1108 return Err(err);
1109 }
1110 return Ok(r);
1111 }
1112 if let Some(provider) = default_repo {
1113 if let Some(r) = provider() {
1114 if let Some(err) = crate::git_refs::validate_repo(&r) {
1115 return Err(err);
1116 }
1117 return Ok(r);
1118 }
1119 }
1120 if let Some(detected) = crate::github::detect_git_repo(".") {
1121 if crate::git_refs::validate_repo(&detected).is_none() {
1122 return Ok(detected);
1123 }
1124 }
1125 Err(
1126 "No active repository. Pass `repo_name='org/repo'`, configure a default in the \
1127 server, or run from a directory whose git remote points at github.com."
1128 .to_string(),
1129 )
1130}
1131
1132pub fn serve_prompts(registry: &ResolvedRegistry, server: &mut McpServer) {
1146 use std::borrow::Cow;
1147 use std::collections::HashSet;
1148
1149 let registered_tools: HashSet<String> = server
1154 .tool_router
1155 .list_all()
1156 .iter()
1157 .map(|t| t.name.to_string())
1158 .collect();
1159 let extensions = server.options.extensions.clone();
1160
1161 struct InjectSkill {
1167 name: String,
1168 description: String,
1169 body: String,
1170 references_tools: Vec<String>,
1171 }
1172 let mut auto_inject: Vec<InjectSkill> = Vec::new();
1173
1174 for name in registry.skill_names() {
1175 let Some(skill) = registry.get(&name) else {
1176 continue;
1177 };
1178
1179 let activation = registry.activation_for(skill, ®istered_tools, &extensions);
1183 if !activation.active {
1184 let failed_clauses: Vec<&str> = activation
1185 .clauses
1186 .iter()
1187 .filter(|(_, outcome)| {
1188 *outcome != crate::server::skills::PredicateOutcome::Satisfied
1189 })
1190 .map(|(clause, _)| clause.as_str())
1191 .collect();
1192 tracing::info!(
1193 skill = %name,
1194 suppressed_by = ?failed_clauses,
1195 "skill suppressed by applies_when predicates"
1196 );
1197 continue;
1198 }
1199
1200 let prompt = Prompt::new(
1201 skill.name().to_string(),
1202 Some(skill.description().to_string()),
1203 None,
1204 );
1205 let body = skill.body.clone();
1206 let route = PromptRoute::new_dyn(prompt, move |_ctx| {
1207 let body = body.clone();
1208 Box::pin(async move {
1209 Ok(GetPromptResult::new(vec![PromptMessage::new_text(
1210 PromptMessageRole::Assistant,
1211 body,
1212 )]))
1213 })
1214 });
1215 server.prompt_router.add_route(route);
1216
1217 if skill.frontmatter.auto_inject_hint {
1218 auto_inject.push(InjectSkill {
1219 name: skill.name().to_string(),
1220 description: skill.description().to_string(),
1221 body: skill.body.clone(),
1222 references_tools: skill.frontmatter.references_tools.clone(),
1223 });
1224 }
1225 }
1226
1227 for inj in &auto_inject {
1263 let mut targets: Vec<&str> = Vec::new();
1266 let mut seen: HashSet<&str> = HashSet::new();
1267 for tool in std::iter::once(inj.name.as_str())
1268 .chain(inj.references_tools.iter().map(String::as_str))
1269 {
1270 if seen.insert(tool) {
1271 targets.push(tool);
1272 }
1273 }
1274
1275 let marker = format!("<!-- mcp-skill:{} -->", inj.name);
1278 let mut block = format!("\n\n{marker}");
1279 let description = inj.description.trim();
1280 if !description.is_empty() {
1281 block.push_str("\n\n## When to use\n\n");
1282 block.push_str(description);
1283 }
1284 block.push_str("\n\n## Methodology\n\n");
1285 block.push_str(inj.body.trim());
1286
1287 for tool in targets {
1288 let key = Cow::<'static, str>::Owned(tool.to_string());
1289 let Some(route) = server.tool_router.map.get_mut(&key) else {
1290 continue;
1291 };
1292 if route
1295 .attr
1296 .description
1297 .as_deref()
1298 .is_some_and(|d| d.contains(&marker))
1299 {
1300 continue;
1301 }
1302 let new_desc = match route.attr.description.take() {
1303 Some(existing) => format!("{existing}{block}"),
1304 None => block.trim_start().to_string(),
1305 };
1306 route.attr.description = Some(Cow::Owned(new_desc));
1307 }
1308 }
1309}
1310
1311#[tool_handler(router = self.tool_router)]
1312impl ServerHandler for McpServer {
1313 fn get_info(&self) -> ServerInfo {
1314 let name = self
1315 .options
1316 .name
1317 .clone()
1318 .unwrap_or_else(|| "MCP Server".to_string());
1319 let mut caps = ServerCapabilities::builder().enable_tools().build();
1326 if !self.prompt_router.map.is_empty() {
1327 caps.prompts = Some(PromptsCapability::default());
1328 }
1329 let mut info = ServerInfo::new(caps)
1330 .with_server_info(Implementation::new(name, env!("CARGO_PKG_VERSION")))
1331 .with_protocol_version(ProtocolVersion::V_2024_11_05);
1332 if let Some(text) = &self.options.instructions {
1333 info = info.with_instructions(text.clone());
1334 }
1335 info
1336 }
1337
1338 async fn list_prompts(
1339 &self,
1340 _request: Option<PaginatedRequestParams>,
1341 _context: rmcp::service::RequestContext<rmcp::RoleServer>,
1342 ) -> Result<ListPromptsResult, McpError> {
1343 Ok(ListPromptsResult {
1344 meta: None,
1345 next_cursor: None,
1346 prompts: self.prompt_router.list_all(),
1347 })
1348 }
1349
1350 async fn get_prompt(
1351 &self,
1352 request: GetPromptRequestParams,
1353 context: rmcp::service::RequestContext<rmcp::RoleServer>,
1354 ) -> Result<GetPromptResult, McpError> {
1355 let prompt_context = rmcp::handler::server::prompt::PromptContext::new(
1356 self,
1357 request.name,
1358 request.arguments,
1359 context,
1360 );
1361 self.prompt_router.get_prompt(prompt_context).await
1362 }
1363}
1364
1365#[cfg(test)]
1366mod tests {
1367 use super::*;
1368
1369 #[test]
1370 fn options_from_manifest_uses_name_when_set() {
1371 let opts = ServerOptions::from_manifest(None, "Fallback");
1372 assert_eq!(opts.name.as_deref(), Some("Fallback"));
1373 }
1374
1375 #[test]
1376 fn builtins_exposed_via_server() {
1377 use crate::server::manifest::{BuiltinsConfig, TempCleanup};
1378 let opts = ServerOptions {
1379 builtins: BuiltinsConfig {
1380 save_graph: true,
1381 temp_cleanup: TempCleanup::OnOverview,
1382 ..Default::default()
1383 },
1384 ..ServerOptions::default()
1385 };
1386 let server = McpServer::new(opts);
1387 assert!(server.builtins().save_graph);
1388 assert_eq!(server.builtins().temp_cleanup, TempCleanup::OnOverview);
1389 }
1390
1391 #[test]
1392 fn server_constructs() {
1393 let _server = McpServer::new(ServerOptions::default());
1394 }
1395
1396 #[test]
1397 fn static_source_roots_provider() {
1398 let opts = ServerOptions::default()
1399 .with_static_source_roots(vec!["/tmp/a".to_string(), "/tmp/b".to_string()]);
1400 let server = McpServer::new(opts);
1401 assert_eq!(
1402 server.current_source_roots(),
1403 vec!["/tmp/a".to_string(), "/tmp/b".to_string()]
1404 );
1405 }
1406
1407 #[test]
1408 fn no_provider_returns_empty_roots() {
1409 let server = McpServer::new(ServerOptions::default());
1410 assert!(server.current_source_roots().is_empty());
1411 }
1412
1413 #[test]
1414 fn repo_management_gated_to_workspace_mode() {
1415 let server = McpServer::new(ServerOptions::default());
1418 let tools = server.tool_router.list_all();
1419 let names: Vec<&str> = tools.iter().map(|t| t.name.as_ref()).collect();
1420 assert!(
1421 !names.contains(&"repo_management"),
1422 "repo_management should be gated out without a workspace; tools were {names:?}"
1423 );
1424 }
1425
1426 #[test]
1427 fn repo_management_present_when_workspace_bound() {
1428 use crate::server::workspace::Workspace;
1431 let dir = tempfile::tempdir().unwrap();
1432 let ws = Workspace::open(dir.path().to_path_buf(), 7, None).unwrap();
1433 let opts = ServerOptions::default().with_workspace(ws);
1434 let server = McpServer::new(opts);
1435 let tools = server.tool_router.list_all();
1436 let names: Vec<&str> = tools.iter().map(|t| t.name.as_ref()).collect();
1437 assert!(
1438 names.contains(&"repo_management"),
1439 "repo_management should be registered with a workspace; tools were {names:?}"
1440 );
1441 }
1442
1443 #[test]
1444 fn result_postprocess_appends_footer_and_sees_ctx() {
1445 use std::sync::Mutex;
1446 type Seen = Option<(String, serde_json::Value, String, Vec<String>)>;
1448 let seen: Arc<Mutex<Seen>> = Arc::new(Mutex::new(None));
1449 let seen_c = seen.clone();
1450 let hook: ResultPostprocessHook = Arc::new(move |tool, args, body, ctx| {
1451 *seen_c.lock().unwrap() = Some((
1452 tool.to_string(),
1453 args.clone(),
1454 body.to_string(),
1455 ctx.source_roots.clone(),
1456 ));
1457 if tool == "grep" {
1459 Some("↳ prefer cypher_query".to_string())
1460 } else {
1461 None
1462 }
1463 });
1464 let opts = ServerOptions::default()
1465 .with_static_source_roots(vec!["/src".to_string()])
1466 .with_result_postprocess(hook);
1467 let server = McpServer::new(opts);
1468
1469 let args = serde_json::json!({ "pattern": "^fn " });
1470 let out = server.finish("grep", &args, "match line".to_string());
1471 assert_eq!(out, "match line\n\n↳ prefer cypher_query");
1472
1473 let rec = seen.lock().unwrap().clone().unwrap();
1474 assert_eq!(rec.0, "grep");
1475 assert_eq!(rec.1, args);
1476 assert_eq!(rec.2, "match line");
1477 assert_eq!(rec.3, vec!["/src".to_string()]);
1478
1479 let out2 = server.finish("read_source", &args, "file body".to_string());
1481 assert_eq!(out2, "file body");
1482 }
1483
1484 #[test]
1485 fn no_result_postprocess_leaves_body_unchanged() {
1486 let server = McpServer::new(ServerOptions::default());
1487 let out = server.finish("grep", &serde_json::Value::Null, "x".to_string());
1488 assert_eq!(out, "x");
1489 }
1490
1491 #[test]
1492 fn append_footer_ignores_empty_footers() {
1493 assert_eq!(append_footer("a".to_string(), None), "a");
1494 assert_eq!(append_footer("a".to_string(), Some(String::new())), "a");
1495 assert_eq!(
1496 append_footer("a".to_string(), Some("b".to_string())),
1497 "a\n\nb"
1498 );
1499 }
1500
1501 #[test]
1502 fn dynamic_provider_swaps_at_call_time() {
1503 use std::sync::Mutex;
1504 let state = Arc::new(Mutex::new(vec!["/initial".to_string()]));
1505 let s2 = state.clone();
1506 let provider: SourceRootsProvider = Arc::new(move || s2.lock().unwrap().clone());
1507 let opts = ServerOptions::default().with_dynamic_source_roots(provider);
1508 let server = McpServer::new(opts);
1509 assert_eq!(server.current_source_roots(), vec!["/initial".to_string()]);
1510 *state.lock().unwrap() = vec!["/swapped".to_string()];
1511 assert_eq!(server.current_source_roots(), vec!["/swapped".to_string()]);
1512 }
1513
1514 fn build_test_registry(
1517 skills: &[(&str, &str, &str, bool)],
1518 ) -> crate::server::skills::ResolvedRegistry {
1519 use crate::server::skills::Registry;
1520 let dir = tempfile::tempdir().unwrap();
1521 let yaml_path = dir.path().join("manifest.yaml");
1522 let skills_dir = dir.path().join("manifest.skills");
1523 std::fs::create_dir_all(&skills_dir).unwrap();
1524 for (name, description, body, auto_inject) in skills {
1525 let auto = if *auto_inject { "true" } else { "false" };
1526 let content = format!(
1527 "---\nname: {name}\ndescription: {description}\nauto_inject_hint: {auto}\n---\n\n{body}\n"
1528 );
1529 std::fs::write(skills_dir.join(format!("{name}.md")), content).unwrap();
1530 }
1531 Registry::new()
1532 .auto_detect_project_layer(&yaml_path)
1533 .finalise()
1534 .unwrap()
1535 }
1536
1537 fn build_registry_with_refs(
1542 skills: &[(&str, &str, &str, &str)],
1543 ) -> crate::server::skills::ResolvedRegistry {
1544 use crate::server::skills::Registry;
1545 let dir = tempfile::tempdir().unwrap();
1546 let yaml_path = dir.path().join("manifest.yaml");
1547 let skills_dir = dir.path().join("manifest.skills");
1548 std::fs::create_dir_all(&skills_dir).unwrap();
1549 for (name, description, body, references_tools) in skills {
1550 let content = format!(
1551 "---\nname: {name}\ndescription: {description}\n\
1552 auto_inject_hint: true\nreferences_tools: {references_tools}\n---\n\n{body}\n"
1553 );
1554 std::fs::write(skills_dir.join(format!("{name}.md")), content).unwrap();
1555 }
1556 Registry::new()
1557 .auto_detect_project_layer(&yaml_path)
1558 .finalise()
1559 .unwrap()
1560 }
1561
1562 fn tool_desc(server: &McpServer, tool: &str) -> String {
1563 server
1564 .tool_router
1565 .get(tool)
1566 .and_then(|t| t.description.clone())
1567 .map(|c| c.into_owned())
1568 .unwrap_or_default()
1569 }
1570
1571 #[test]
1572 fn prompt_router_empty_by_default() {
1573 let server = McpServer::new(ServerOptions::default());
1574 assert!(server.prompt_router.map.is_empty());
1575 }
1576
1577 #[test]
1578 fn get_info_no_prompts_capability_when_empty() {
1579 let server = McpServer::new(ServerOptions::default());
1583 let info = server.get_info();
1584 assert!(
1585 info.capabilities.prompts.is_none(),
1586 "prompts capability must be absent when no skills are registered"
1587 );
1588 }
1589
1590 #[test]
1591 fn serve_prompts_registers_routes_with_metadata() {
1592 let registry = build_test_registry(&[
1593 ("alpha", "First skill.", "Alpha body.", true),
1594 ("beta", "Second skill.", "Beta body.", true),
1595 ]);
1596 let mut server = McpServer::new(ServerOptions::default());
1597 super::serve_prompts(®istry, &mut server);
1598
1599 let prompts = server.prompt_router.list_all();
1600 let names: Vec<&str> = prompts.iter().map(|p| p.name.as_str()).collect();
1601 assert_eq!(names, vec!["alpha", "beta"]);
1602
1603 let alpha = prompts.iter().find(|p| p.name == "alpha").unwrap();
1604 assert_eq!(alpha.description.as_deref(), Some("First skill."));
1605 assert!(alpha.arguments.is_none());
1606 }
1607
1608 #[test]
1609 fn serve_prompts_empty_registry_is_noop() {
1610 let registry = crate::server::skills::ResolvedRegistry::default();
1611 let mut server = McpServer::new(ServerOptions::default());
1612 super::serve_prompts(®istry, &mut server);
1613 assert!(server.prompt_router.map.is_empty());
1614 assert!(server.get_info().capabilities.prompts.is_none());
1615 }
1616
1617 #[test]
1618 fn get_info_advertises_prompts_when_present() {
1619 let registry = build_test_registry(&[("alpha", "First skill.", "Alpha body.", true)]);
1620 let mut server = McpServer::new(ServerOptions::default());
1621 super::serve_prompts(®istry, &mut server);
1622 let info = server.get_info();
1623 assert!(
1624 info.capabilities.prompts.is_some(),
1625 "prompts capability must be advertised once a skill is registered"
1626 );
1627 }
1628
1629 #[test]
1630 fn serve_prompts_auto_injects_full_body_into_matching_tool() {
1631 let registry =
1639 build_test_registry(&[("ping", "Ping methodology.", "PING-BODY-SENTINEL", true)]);
1640 let mut server = McpServer::new(ServerOptions::default());
1641 let before = server
1642 .tool_router
1643 .get("ping")
1644 .and_then(|t| t.description.clone())
1645 .map(|c| c.into_owned())
1646 .unwrap_or_default();
1647 super::serve_prompts(®istry, &mut server);
1648 let after = server
1649 .tool_router
1650 .get("ping")
1651 .and_then(|t| t.description.clone())
1652 .map(|c| c.into_owned())
1653 .unwrap_or_default();
1654 assert!(after.starts_with(&before), "original description preserved");
1655 assert!(
1656 after.contains("## Methodology"),
1657 "inject should include a Methodology header; got: {after}"
1658 );
1659 assert!(
1660 after.contains("PING-BODY-SENTINEL"),
1661 "inject should embed the full skill body; got: {after}"
1662 );
1663 assert!(
1664 !after.contains("prompts/get"),
1665 "post-0.3.37 inject should NOT reference the prompts/get surface (agents can't reach it); got: {after}"
1666 );
1667 }
1668
1669 #[test]
1670 fn serve_prompts_skips_injection_when_disabled() {
1671 let registry = build_test_registry(&[("ping", "Ping methodology.", "Ping body.", false)]);
1672 let mut server = McpServer::new(ServerOptions::default());
1673 let before = server
1674 .tool_router
1675 .get("ping")
1676 .and_then(|t| t.description.clone())
1677 .map(|c| c.into_owned())
1678 .unwrap_or_default();
1679 super::serve_prompts(®istry, &mut server);
1680 let after = server
1681 .tool_router
1682 .get("ping")
1683 .and_then(|t| t.description.clone())
1684 .map(|c| c.into_owned())
1685 .unwrap_or_default();
1686 assert_eq!(
1687 before, after,
1688 "auto_inject_hint=false must leave tool description untouched"
1689 );
1690 }
1691
1692 #[test]
1693 fn serve_prompts_skips_injection_when_no_matching_tool() {
1694 let registry = build_test_registry(&[("no_such_tool", "Methodology.", "Body.", true)]);
1697 let mut server = McpServer::new(ServerOptions::default());
1698 super::serve_prompts(®istry, &mut server);
1699 assert!(server.prompt_router.map.contains_key("no_such_tool"));
1700 let ping_desc = server
1703 .tool_router
1704 .get("ping")
1705 .and_then(|t| t.description.clone())
1706 .map(|c| c.into_owned())
1707 .unwrap_or_default();
1708 assert!(!ping_desc.contains("no_such_tool"));
1709 }
1710
1711 #[test]
1712 fn serve_prompts_injects_description_under_when_to_use() {
1713 let registry = build_test_registry(&[("ping", "ROUTING-SENTINEL", "BODY-SENTINEL", true)]);
1717 let mut server = McpServer::new(ServerOptions::default());
1718 super::serve_prompts(®istry, &mut server);
1719 let desc = tool_desc(&server, "ping");
1720 assert!(
1721 desc.contains("## When to use\n\nROUTING-SENTINEL"),
1722 "description should be injected under `## When to use`; got: {desc}"
1723 );
1724 assert!(
1725 desc.contains("<!-- mcp-skill:ping -->"),
1726 "injection should carry the per-skill idempotency marker; got: {desc}"
1727 );
1728 let when = desc.find("## When to use").unwrap();
1730 let method = desc.find("## Methodology").unwrap();
1731 assert!(when < method, "`When to use` must precede `Methodology`");
1732 }
1733
1734 #[test]
1735 fn serve_prompts_honors_references_tools() {
1736 let registry = build_registry_with_refs(&[(
1740 "graph_strategy",
1741 "Map structure first.",
1742 "GRAPH-BODY-SENTINEL",
1743 "[ping]",
1744 )]);
1745 let mut server = McpServer::new(ServerOptions::default());
1746 super::serve_prompts(®istry, &mut server);
1747 assert!(server.prompt_router.map.contains_key("graph_strategy"));
1749 let desc = tool_desc(&server, "ping");
1751 assert!(
1752 desc.contains("<!-- mcp-skill:graph_strategy -->"),
1753 "referenced tool should carry the skill marker; got: {desc}"
1754 );
1755 assert!(
1756 desc.contains("Map structure first."),
1757 "referenced tool should carry the skill routing; got: {desc}"
1758 );
1759 assert!(
1760 desc.contains("GRAPH-BODY-SENTINEL"),
1761 "referenced tool should carry the skill body; got: {desc}"
1762 );
1763 }
1764
1765 #[test]
1766 fn serve_prompts_idempotent_when_skill_self_references() {
1767 let registry = build_registry_with_refs(&[("ping", "Routing.", "Body.", "[ping]")]);
1771 let mut server = McpServer::new(ServerOptions::default());
1772 super::serve_prompts(®istry, &mut server);
1773 let desc = tool_desc(&server, "ping");
1774 let marker_count = desc.matches("<!-- mcp-skill:ping -->").count();
1775 assert_eq!(
1776 marker_count, 1,
1777 "self-referencing skill must inject exactly once; got {marker_count}: {desc}"
1778 );
1779 }
1780
1781 #[test]
1782 fn serve_prompts_idempotent_across_repeated_passes() {
1783 let registry = build_test_registry(&[("ping", "Routing.", "Body.", true)]);
1786 let mut server = McpServer::new(ServerOptions::default());
1787 super::serve_prompts(®istry, &mut server);
1788 let once = tool_desc(&server, "ping");
1789 super::serve_prompts(®istry, &mut server);
1790 let twice = tool_desc(&server, "ping");
1791 assert_eq!(
1792 once, twice,
1793 "second pass must be a no-op for an already-injected tool"
1794 );
1795 }
1796
1797 #[test]
1798 fn serve_prompts_multiple_skills_stack_on_one_tool() {
1799 let registry = build_registry_with_refs(&[
1803 ("ping", "Ping routing.", "PING-BODY", "[]"),
1804 ("ping_strategy", "Strategy routing.", "STRAT-BODY", "[ping]"),
1805 ]);
1806 let mut server = McpServer::new(ServerOptions::default());
1807 super::serve_prompts(®istry, &mut server);
1808 let desc = tool_desc(&server, "ping");
1809 assert!(desc.contains("<!-- mcp-skill:ping -->"), "got: {desc}");
1810 assert!(
1811 desc.contains("<!-- mcp-skill:ping_strategy -->"),
1812 "got: {desc}"
1813 );
1814 assert!(
1815 desc.contains("PING-BODY") && desc.contains("STRAT-BODY"),
1816 "got: {desc}"
1817 );
1818 }
1819
1820 fn write_gated_project_skill(applies_when_yaml: &str) -> tempfile::TempDir {
1821 let dir = tempfile::tempdir().unwrap();
1822 let yaml = dir.path().join("test_mcp.yaml");
1823 std::fs::write(&yaml, "name: t\nskills: true\n").unwrap();
1824 let skills_dir = dir.path().join("test_mcp.skills");
1825 std::fs::create_dir(&skills_dir).unwrap();
1826 std::fs::write(
1827 skills_dir.join("gated_skill.md"),
1828 format!(
1829 "---\n\
1830 name: gated_skill\n\
1831 description: A predicate-gated skill for testing.\n\
1832 applies_when:\n\
1833 {applies_when_yaml}\n\
1834 ---\n\n\
1835 Body.\n",
1836 ),
1837 )
1838 .unwrap();
1839 dir
1840 }
1841
1842 #[test]
1843 fn serve_prompts_suppresses_skill_with_unsatisfied_predicate() {
1844 use crate::server::skills::Registry as SkillsBuilder;
1848 let dir = write_gated_project_skill(" tool_registered: nonexistent_tool");
1849 let yaml = dir.path().join("test_mcp.yaml");
1850 let registry = SkillsBuilder::new()
1851 .auto_detect_project_layer(&yaml)
1852 .finalise()
1853 .unwrap();
1854 let mut server = McpServer::new(ServerOptions::default());
1855 super::serve_prompts(®istry, &mut server);
1856 assert!(
1857 !server.prompt_router.map.contains_key("gated_skill"),
1858 "skill with unsatisfied predicate must be suppressed"
1859 );
1860 }
1861
1862 #[test]
1863 fn serve_prompts_keeps_skill_with_satisfied_predicate() {
1864 use crate::server::skills::Registry as SkillsBuilder;
1867 let dir = write_gated_project_skill(" tool_registered: ping");
1868 let yaml = dir.path().join("test_mcp.yaml");
1869 let registry = SkillsBuilder::new()
1870 .auto_detect_project_layer(&yaml)
1871 .finalise()
1872 .unwrap();
1873 let mut server = McpServer::new(ServerOptions::default());
1874 super::serve_prompts(®istry, &mut server);
1875 assert!(
1876 server.prompt_router.map.contains_key("gated_skill"),
1877 "skill with satisfied predicate must register"
1878 );
1879 }
1880
1881 #[test]
1882 fn serve_prompts_evaluates_extension_enabled_from_manifest() {
1883 use crate::server::skills::Registry as SkillsBuilder;
1887 let dir = write_gated_project_skill(" extension_enabled: csv_http_server");
1888 let yaml = dir.path().join("test_mcp.yaml");
1889 let registry = SkillsBuilder::new()
1890 .auto_detect_project_layer(&yaml)
1891 .finalise()
1892 .unwrap();
1893
1894 let mut server = McpServer::new(ServerOptions::default());
1896 super::serve_prompts(®istry, &mut server);
1897 assert!(!server.prompt_router.map.contains_key("gated_skill"));
1898
1899 let mut extensions = serde_json::Map::new();
1901 extensions.insert("csv_http_server".to_string(), serde_json::json!(true));
1902 let opts = ServerOptions {
1903 extensions,
1904 ..ServerOptions::default()
1905 };
1906 let mut server = McpServer::new(opts);
1907 super::serve_prompts(®istry, &mut server);
1908 assert!(server.prompt_router.map.contains_key("gated_skill"));
1909 }
1910}