akshare-mcp 0.1.11

MCP server for akshare-rs — financial market data via Model Context Protocol
Documentation
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! MCP tool definitions for akshare financial data.
//!
//! Tools are auto-discovered from `AkShareClient` methods by `build.rs`.
//! Only two meta-tools are exposed via MCP: `tools/search` and `tools/call`.

pub mod bond;
pub mod crypto;
pub mod economy;
pub mod forex;
pub mod fund;
pub mod futures;
pub mod index;
pub mod macro_data;
pub mod news;
pub mod option;
pub mod stock;

use std::collections::HashMap;
use std::sync::{Arc, LazyLock};

use akshare::AkShareClient;
use rmcp::{
    ErrorData as McpError, RoleServer, ServerHandler,
    handler::server::tool::schema_for_type,
    model::{
        CallToolRequestParams, CallToolResult, Content, Implementation, PaginatedRequestParams,
        ServerCapabilities, ServerInfo, Tool,
    },
    schemars,
    service::RequestContext,
};

use crate::config::ToolsConfig;

// ── Tool registry types ──────────────────────────────────────────────

type Handler = fn(
    &AkShareClient,
    serde_json::Value,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = Result<serde_json::Value, String>> + Send>,
>;

pub(crate) struct ToolEntry {
    pub description: &'static str,
    pub category: &'static str,
    pub schema: Arc<serde_json::Map<String, serde_json::Value>>,
    pub handler: Handler,
}

/// Register a tool in the registry.
/// The closure `|$client, $p| $body` must return `Pin<Box<dyn Future<...> + Send>>`.
/// The macro deserializes `$p` from the JSON args and calls the closure.
macro_rules! register_tool {
    ($registry:expr, $name:expr, $desc:expr, $cat:expr, $ptype:ty, |$client:ident, $p:ident| $body:expr) => {{
        let handler: crate::tools::Handler = |client, args| {
            Box::pin({
                let $client = client.clone();
                async move {
                    let $p: $ptype = serde_json::from_value(args).map_err(|e| e.to_string())?;
                    $body.await
                }
            })
        };
        $registry.insert(
            $name,
            crate::tools::ToolEntry {
                description: $desc,
                category: $cat,
                schema: rmcp::handler::server::tool::schema_for_type::<$ptype>(),
                handler,
            },
        );
    }};
}

// Include the auto-generated tool registry from `build.rs`.
include!(concat!(env!("OUT_DIR"), "/tool_registry.rs"));

static TOOL_REGISTRY: LazyLock<HashMap<&'static str, ToolEntry>> = LazyLock::new(|| {
    let mut m = HashMap::new();
    load_registry(&mut m);
    m
});

// ── Category prefixes for filtering ──────────────────────────────────

const CATEGORY_PREFIXES: &[(&str, &[&str])] = &[
    ("stock", &["stock_", "a_share_", "hk_", "us_", "get_us_"]),
    ("bond", &["bond_"]),
    ("index", &["index_"]),
    ("futures", &["futures_"]),
    (
        "economy",
        &[
            "economy_",
            "movie_",
            "nlp_",
            "amac_",
            "car_",
            "sw_",
            "fx_",
            "article_",
            "air_",
            "qdii_",
            "video_",
            "sunrise_",
            "repo_",
            "migration_",
            "fred_",
            "xincaifu_",
            "spot_",
            "sogou_",
            "rate_",
            "online_",
            "match_",
            "hurun_",
            "hf_",
            "google_",
            "gdelt_",
            "game_",
            "forbes_",
            "drewry_",
            "business_",
            "bing_",
            "baidu_",
            "qhkc_",
            "methods_in_",
        ],
    ),
    ("crypto", &["crypto_"]),
    ("forex", &["forex_", "currency_"]),
    ("option", &["option_"]),
    ("news", &["news_"]),
    ("macro_data", &["macro_"]),
    ("fund", &["fund_"]),
];

// ── Meta-tool param types ──────────────────────────────────────────

#[derive(serde::Deserialize, schemars::JsonSchema)]
struct ToolsSearchParams {
    /// Keyword to match against tool name or description.
    query: Option<String>,
    /// Filter by category: stock, bond, index, futures, economy, crypto, forex, option, news, macro_data, fund.
    category: Option<String>,
}

#[derive(serde::Deserialize, schemars::JsonSchema)]
struct ToolsCallParams {
    /// Exact tool name (use tools/search to discover).
    name: String,
    /// JSON object of parameters to pass to the tool.
    arguments: Option<serde_json::Map<String, serde_json::Value>>,
}

// ── Service ──────────────────────────────────────────────────────────

/// MCP service exposing akshare financial data via `tools/search` + `tools/call`.
#[derive(Clone)]
pub struct AkShareMcpService {
    client: AkShareClient,
    enabled_categories: Vec<String>,
}

impl AkShareMcpService {
    #[must_use]
    pub fn new(tools_config: ToolsConfig) -> Self {
        Self {
            client: AkShareClient::new(),
            enabled_categories: Self::enabled_categories(&tools_config),
        }
    }

    fn enabled_categories(config: &ToolsConfig) -> Vec<String> {
        CATEGORY_PREFIXES
            .iter()
            .filter(|(cat, _)| config.is_enabled(cat))
            .map(|(cat, _)| (*cat).to_string())
            .collect()
    }

    fn is_category_enabled(&self, category: &str) -> bool {
        self.enabled_categories.iter().any(|c| c == category)
    }

    /// Build the 2 meta-tools for MCP `list_tools`.
    fn meta_tools() -> Vec<Tool> {
        vec![
            Tool::new_with_raw(
                "tools/search",
                Some("Search available tools by keyword and/or category. Returns matching tool names and descriptions. Use this before tools/call to discover the exact tool name.".into()),
                schema_for_type::<ToolsSearchParams>(),
            ),
            Tool::new_with_raw(
                "tools/call",
                Some("Call any tool by name with JSON arguments. Use tools/search first to discover available tools and their parameter schemas.".into()),
                schema_for_type::<ToolsCallParams>(),
            ),
        ]
    }

    /// Search the tool registry by optional category and/or keyword.
    fn search_registry(
        &self,
        category: Option<&str>,
        query: Option<&str>,
    ) -> Vec<(String, String)> {
        let query_lower = query.map(|q| q.to_lowercase());
        let category_prefixes: Option<&[&str]> = category
            .and_then(|cat| CATEGORY_PREFIXES.iter().find(|(name, _)| *name == cat))
            .map(|(_, prefixes)| *prefixes);

        TOOL_REGISTRY
            .iter()
            .filter(|(name, entry)| {
                if !self.is_category_enabled(entry.category) {
                    return false;
                }
                if let Some(prefixes) = category_prefixes
                    && !prefixes.iter().any(|p| name.starts_with(p))
                {
                    return false;
                }
                if let Some(ref q) = query_lower {
                    let name_match = name.to_lowercase().contains(q.as_str());
                    let desc_match = entry.description.to_lowercase().contains(q.as_str());
                    if !name_match && !desc_match {
                        return false;
                    }
                }
                true
            })
            .map(|(name, entry)| (name.to_string(), entry.description.to_string()))
            .collect()
    }
}

// ── MCP handler ──────────────────────────────────────────────────────

impl ServerHandler for AkShareMcpService {
    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        match request.name.as_ref() {
            "tools/search" => {
                let args: ToolsSearchParams = request
                    .arguments
                    .map(|obj| {
                        serde_json::from_value(serde_json::Value::Object(obj)).map_err(|e| {
                            McpError::invalid_params(
                                format!("failed to deserialize parameters: {e}"),
                                None,
                            )
                        })
                    })
                    .transpose()?
                    .unwrap_or(ToolsSearchParams {
                        query: None,
                        category: None,
                    });

                let results: Vec<serde_json::Value> = self
                    .search_registry(args.category.as_deref(), args.query.as_deref())
                    .into_iter()
                    .map(|(name, desc)| serde_json::json!({ "name": name, "description": desc }))
                    .collect();

                Ok(CallToolResult::success(vec![Content::text(
                    serde_json::to_string_pretty(&results).unwrap(),
                )]))
            }
            "tools/call" => {
                let args: ToolsCallParams = request
                    .arguments
                    .map(|obj| {
                        serde_json::from_value(serde_json::Value::Object(obj)).map_err(|e| {
                            McpError::invalid_params(
                                format!("failed to deserialize parameters: {e}"),
                                None,
                            )
                        })
                    })
                    .transpose()?
                    .ok_or_else(|| McpError::invalid_params("missing arguments", None))?;

                let entry = TOOL_REGISTRY.get(args.name.as_str()).ok_or_else(|| {
                    McpError::invalid_params(format!("unknown tool: {}", args.name), None)
                })?;

                if !self.is_category_enabled(entry.category) {
                    return Err(McpError::invalid_params(
                        format!("tool category '{}' is disabled", entry.category),
                        None,
                    ));
                }

                let args_value = args
                    .arguments
                    .map(serde_json::Value::Object)
                    .unwrap_or(serde_json::Value::Null);

                let handler = entry.handler;
                let result = handler(&self.client, args_value)
                    .await
                    .map_err(|e| McpError::internal_error(e, None))?;

                Ok(CallToolResult::success(vec![Content::text(
                    serde_json::to_string_pretty(&result).unwrap(),
                )]))
            }
            _ => Err(McpError::invalid_params(
                format!(
                    "unknown tool: {}. Use tools/search to discover available tools.",
                    request.name
                ),
                None,
            )),
        }
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<rmcp::model::ListToolsResult, McpError> {
        let mut tools = Self::meta_tools();

        // Add all registry tools whose category is enabled
        for (name, entry) in TOOL_REGISTRY.iter() {
            if self.is_category_enabled(entry.category) {
                tools.push(Tool::new_with_raw(
                    *name,
                    Some(entry.description.into()),
                    entry.schema.clone(),
                ));
            }
        }

        Ok(rmcp::model::ListToolsResult {
            tools,
            meta: None,
            next_cursor: None,
        })
    }

    fn get_tool(&self, name: &str) -> Option<Tool> {
        if name == "tools/search" || name == "tools/call" {
            return Self::meta_tools()
                .into_iter()
                .find(|t| t.name.as_ref() == name);
        }
        TOOL_REGISTRY.get(name).and_then(|entry| {
            if self.is_category_enabled(entry.category) {
                Some(Tool::new_with_raw(
                    name.to_string(),
                    Some(entry.description.into()),
                    entry.schema.clone(),
                ))
            } else {
                None
            }
        })
    }

    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::from_build_env())
            .with_instructions(
                "Financial market data MCP server powered by akshare-rs. \
                 Use tools/search to discover available tools, then tools/call to invoke them. \
                 Provides tools for A-share, HK, US stocks, funds, bonds, \
                 futures, options, forex, crypto, macro data, economy, and news."
                    .to_string(),
            )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_service_creates() {
        let service = AkShareMcpService::new(ToolsConfig::all());
        let info = service.get_info();
        assert!(info.capabilities.tools.is_some());
    }

    #[test]
    fn test_service_info_instructions() {
        let service = AkShareMcpService::new(ToolsConfig::all());
        let info = service.get_info();
        let instructions = info.instructions.unwrap();
        assert!(instructions.contains("akshare-rs"));
    }

    #[test]
    fn test_service_clone() {
        let service = AkShareMcpService::new(ToolsConfig::all());
        let cloned = service;
        let info = cloned.get_info();
        assert!(info.capabilities.tools.is_some());
    }

    #[test]
    fn test_list_tools_has_meta_tools() {
        let service = AkShareMcpService::new(ToolsConfig::all());
        let tools = service.list_tools_sync();
        let names: Vec<&str> = tools.iter().map(|t| t.name.as_ref()).collect();
        assert!(names.contains(&"tools/search"));
        assert!(names.contains(&"tools/call"));
    }

    #[test]
    fn test_list_tools_has_registry_tools() {
        let service = AkShareMcpService::new(ToolsConfig::all());
        let tools = service.list_tools_sync();
        // Should have at least the 2 meta-tools + some registry tools
        assert!(tools.len() > 2, "expected registry tools to be listed");
    }

    #[test]
    fn test_get_tool_meta_tools() {
        let service = AkShareMcpService::new(ToolsConfig::all());
        assert!(service.get_tool("tools/search").is_some());
        assert!(service.get_tool("tools/call").is_some());
    }

    #[test]
    fn test_category_filter() {
        let cfg = ToolsConfig {
            bond: true,
            ..ToolsConfig::default()
        };
        let service = AkShareMcpService::new(cfg);
        let results = service.search_registry(None, None);
        let has_bond = results.iter().any(|(n, _)| n.starts_with("bond_"));
        let has_futures = results.iter().any(|(n, _)| n.starts_with("futures_"));
        assert!(has_bond, "bond tools should be enabled");
        assert!(!has_futures, "futures tools should be disabled");
    }

    #[test]
    fn test_search_by_keyword() {
        let service = AkShareMcpService::new(ToolsConfig::all());
        let results = service.search_registry(None, Some("quote"));
        assert!(!results.is_empty(), "searching 'quote' should find tools");
        for (name, desc) in &results {
            assert!(
                name.to_lowercase().contains("quote") || desc.to_lowercase().contains("quote"),
                "result should match query: {}",
                name
            );
        }
    }

    #[test]
    fn test_search_by_category() {
        let service = AkShareMcpService::new(ToolsConfig::all());
        let results = service.search_registry(Some("stock"), None);
        assert!(!results.is_empty(), "stock category should have tools");
        for (name, _) in &results {
            assert!(
                name.starts_with("stock_")
                    || name.starts_with("a_share_")
                    || name.starts_with("hk_")
                    || name.starts_with("us_")
                    || name.starts_with("get_us_"),
                "all results should be stock tools, got: {}",
                name
            );
        }
    }

    // Backward compat: list_tools_sync helper
    impl AkShareMcpService {
        fn list_tools_sync(&self) -> Vec<Tool> {
            let mut tools = Self::meta_tools();
            for (name, entry) in TOOL_REGISTRY.iter() {
                if self.is_category_enabled(entry.category) {
                    tools.push(Tool::new_with_raw(
                        *name,
                        Some(entry.description.into()),
                        entry.schema.clone(),
                    ));
                }
            }
            tools
        }
    }
}