MCP tool schema design for stock market data comes down to one idea: the tool definition is the only documentation the model reads before it acts, so every ambiguity in a name, parameter or return field becomes a wrong call or, worse, a confident wrong sentence. A good financial tool states which question it answers, which identifiers it accepts, what time the numbers refer to, and what kind of source they come from.

This post builds a small read-only MCP server in Python for A-share research data and uses it to walk through the decisions that matter: naming, input constraints, structured output, provenance labels, time fields and error messages. The server runs offline with demo data, so you can test the schema before connecting any real source. Codes and company names in the examples are placeholders for method demonstration.

What the model actually sees

A tool in the MCP specification has a name, an optional title, a description, an inputSchema (JSON Schema), an optional outputSchema, and optional annotations such as readOnlyHint and idempotentHint. The client puts these definitions into the model's context on every turn. The model never sees your database schema, your vendor docs or your README.

That has two consequences for market data:

  • Descriptions are prompts. They should say what question the tool answers, its scope (one stock or the whole market, current or historical), units, and when to use a sibling tool instead.
  • Definitions cost context. Ten verbose tools can crowd out the conversation. Prefer several focused tools with tight descriptions over one tool with a free-text query parameter.

Name tools after the question, not the table

Compare query_stock_table with get_stock_concepts and get_company_profile. The first forces the model to guess what the table holds. The second pair answers two different questions a user might ask: "which themes is this stock tagged with?" and "what does this company actually do?"

A useful naming pattern for read-only financial tools is get_<entity>_<facet> or list_<entities>_by_<criterion>. Keep the direction explicit when two tools are inverses. "Stock to concepts" and "concept to stocks" should be two tools with names that make the direction obvious, not one tool with a direction flag.

Constrain inputs so invalid calls fail early

Identifier confusion is the most common failure with stock tools. Models will pass 300750.SZ, SZ300750, a company name, or a Hong Kong code. Put the format in the schema, not only in prose:

  • A regex pattern for codes, with an example in the description.
  • minimum and maximum for lookbacks and limits, with the default stated.
  • enum (in Python, Literal) for finite choices like time windows: "1h" | "4h" | "24h" | "3d" | "7d". A model cannot invent "2w" if the enum doesn't allow it.
  • Mark only truly required fields as required. Everything else gets a default.

With the official Python SDK, Annotated[..., Field(...)] turns those constraints into JSON Schema automatically. Pydantic then validates every call before your function runs, so a bad code never reaches your data layer.

Return structured output with provenance

Free-text tool results are hard to cite and easy to misread. Return a typed object; the SDK derives an outputSchema from the return annotation and sends both structuredContent and a JSON text block.

For financial research, add a provenance block to every result. Three fields do most of the work:

Field Purpose
source_type filing, market_tag or discussion. Keeps disclosed facts, classification labels and public commentary apart.
as_of When the payload was computed, ISO-8601 with an explicit offset such as +08:00.
point_in_time Whether the value can be reproduced for a past date. Tells the model and the user whether it is safe for historical analysis.

The source_type split matters more than it looks. A company's filed main business, a concept tag assigned by a data vendor, and what commentators said last week are three different kinds of evidence. When a tool merges them, the model happily writes "the company's AI business is growing" from a tag and two blog posts. When they are labeled, you can instruct the model to quote filings for business facts and treat tags and discussion as context.

A complete example server

The code below uses the official mcp Python SDK. In SDK 2.x the high-level class is MCPServer in mcp.server.mcpserver; in 1.x the same decorator API lived in FastMCP under mcp.server.fastmcp, so adjust the import if you pin the older version.

from datetime import datetime, timedelta, timezone from typing import Annotated, Literal from pydantic import BaseModel, Field from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.exceptions import ToolError from mcp.types import ToolAnnotations CST = timezone(timedelta(hours=8)) READ_ONLY = ToolAnnotations(readOnlyHint=True, idempotentHint=True, openWorldHint=False) server = MCPServer("a-share-research-demo") SourceType = Literal["filing", "market_tag", "discussion"] Code = Annotated[str, Field(pattern=r"^\d{6}$", description="6-digit A-share code without suffix, e.g. 300750.")] class Provenance(BaseModel): source_type: SourceType = Field(description="filing = company disclosure; market_tag = classification label; " "discussion = public commentary. Never merge them in one sentence.") as_of: str = Field(description="When this payload was computed, ISO-8601 with +08:00.") point_in_time: bool = Field(description="True only if the value can be reproduced for a past date.") class Profile(BaseModel): code: str name: str main_business: str = Field(description="Main business as stated in filings. Quoted, not paraphrased.") listed_on: str = Field(description="Listing date, YYYY-MM-DD.") provenance: Provenance class ConceptRow(BaseModel): concept: str = Field(description="Standard concept name. Pass it unchanged to other tools.") mention_share_7d: float = Field(description="Share of this concept's last-7-day mentions that involve the stock, 0..1.") class ConceptList(BaseModel): code: str rows: list[ConceptRow] truncated: bool = Field(description="True if more concepts exist than were returned.") provenance: Provenance # demo data so the server runs offline PROFILES = {"999001": ("DEMO AI CHIP CO", "Design and sale of AI processor chips and related software.", "2020-07-20")} CONCEPTS = {"999001": [("AI chips", 0.12), ("Computing power", 0.05), ("Semiconductors", 0.02)]} def now() -> str: return datetime.now(CST).isoformat(timespec="seconds") @server.tool(annotations=READ_ONLY) def get_company_profile(code: Code) -> Profile: """What does this listed company do, according to its own disclosures? Returns main business and listing date from filings only. Contains no concept tags, no discussion and no prices. For theme tags call get_stock_concepts.""" if code not in PROFILES: raise ToolError(f"Unknown code {code}. Use a 6-digit A-share code; " "Hong Kong and US listings are not covered.") name, business, listed = PROFILES[code] return Profile(code=code, name=name, main_business=business, listed_on=listed, provenance=Provenance(source_type="filing", as_of=now(), point_in_time=True)) @server.tool(annotations=READ_ONLY) def get_stock_concepts( code: Code, limit: Annotated[int, Field(ge=1, le=50, description="Max concepts to return. Default 15.")] = 15, ) -> ConceptList: """Which concept tags is this stock currently classified under? Ordered by the stock's share of each concept's mentions over the last 7 days. Current membership only: removed concepts are not returned and there is no history. A tag is a classification, not evidence of revenue. For business facts use get_company_profile.""" rows = [ConceptRow(concept=c, mention_share_7d=s) for c, s in CONCEPTS.get(code, [])] return ConceptList(code=code, rows=rows[:limit], truncated=len(rows) > limit, provenance=Provenance(source_type="market_tag", as_of=now(), point_in_time=False)) if __name__ == "__main__": server.run() # stdio transport by default 

Install with pip install mcp, save as server.py, and point any MCP client at python /absolute/path/server.py. Inspecting the generated schema for get_stock_concepts shows the constraints arriving intact:

{ "properties": { "code": {"type": "string", "pattern": "^\\d{6}$", "description": "6-digit A-share code without suffix, e.g. 300750."}, "limit": {"type": "integer", "minimum": 1, "maximum": 50, "default": 15, "description": "Max concepts to return. Default 15."} }, "required": ["code"], "type": "object" } 

Decisions worth copying

Descriptions point to siblings. Each docstring says what the tool does not contain and which tool to call instead. This is the cheapest way to stop a model from answering a business question from a concept tag.

Units and ranges live on fields. mention_share_7d says it is a share between 0 and 1 over seven days. Without that, a model may describe 0.12 as "12 mentions" or "12% growth".

Truncation is explicit. truncated: true tells the model the list is partial. Otherwise it will say "this stock belongs to exactly 15 concepts" whenever limit is 15.

point_in_time is honest. The concept tool returns current membership, so it says false. A model asked "which themes did this stock belong to in March?" now has a field telling it that this tool cannot answer, instead of returning today's list as if it were history.

Annotations describe behavior. readOnlyHint=True and idempotentHint=True let clients skip confirmation prompts and retry safely. Leave them off for anything that writes, places orders or sends messages.

Errors the model can recover from

There are two failure layers and both should produce readable text.

  1. Validation errors happen before your function runs. Passing 300750.SZ produces a message that names the field and the pattern. The model usually corrects the code and retries on its own.
  2. Domain errors come from your code. Raise ToolError with a message that says what went wrong and what to do next: unknown code, unsupported market, window out of range. Avoid bare exceptions like KeyError: '000000'; they tell the model nothing.

Never return an empty list for "unknown code". An empty rows should mean "known stock, no tags", and an error should mean "I could not look this up". Mixing them leads to claims like "this company has no concept exposure".

Testing a schema before you trust it

Three quick checks before connecting a real data source:

  • List tools in a client or the MCP Inspector and read each description as if you had never seen the code. If you can't tell which tool answers "what does the company do?", neither can the model.
  • Call each tool with three inputs: a valid one, a wrongly formatted code, and a well-formed code you don't cover. Confirm you get data, a validation message and a domain error respectively.
  • Ask the model five real questions and log which tools it chose. Misrouted calls are almost always a description problem, not a model problem.

Keep tool outputs as dicts and lists, not pre-formatted tables. Structured output can be cited field by field and checked in logs; a printed table can't.

A reference for separating source types

If you want a concrete picture of what the filing / tag / discussion separation looks like for real companies, Lava (熔岩) keeps a public question-and-answer library that shows company disclosures, market concept labels and AI-summarized discussion in separate sections per stock. Lava monitors A-share news-flow heat from institutions and KOLs and serves it to quant and agent workflows through REST and MCP, so its research pages are a reasonable model for how tool outputs should label provenance. Browse the stock research Q&A library to see the pattern before you design your own source_type values.

FAQ

Should I return text or structured content from an MCP tool?
Return a typed object. The Python SDK sends it as structuredContent and also as a JSON text block, so clients that don't read structured output still work.

How many tools should a market data server expose?
As many as there are distinct questions, and no more. Five to ten focused tools is typical. If two tools always get called together, consider merging them; if one tool takes a mode flag that changes its meaning, split it.

Where should timezone handling live?
In the server. Return every timestamp with an explicit offset and state the market's local zone in descriptions. Never return naive times and hope the model infers the zone.

Can the model see my OpenAPI docs?
Not unless you paste them into the tool description. Anything the model needs to choose and call the tool correctly must be in the tool definition itself.

Conclusion

Good MCP tool schema design for stock market data is mostly careful writing backed by a few strict types. Name tools after the question, constrain identifiers and ranges in JSON Schema, return structured objects, and label every result with source_type, as_of and point_in_time. Add errors the model can act on, test with real questions, and the model will make fewer calls, pick the right tool more often, and cite numbers with the context they need.

中文简介:本文讲股票数据 MCP 工具的 schema 设计:按问题命名工具、用 JSON Schema 约束代码格式与参数范围、返回结构化对象,并为每个结果加上 source_type、as_of、point_in_time 三个来源字段,把公告事实、概念标签和公开讨论分开。文中给出基于官方 Python SDK 的可运行示例服务器和错误处理写法,示例代码与公司均为演示占位。