nanomcp
nanomcp
이것은 MCP Python SDK 없이 직접 작성한 최소한의 MCP 데모입니다. 전체 링크를 포함합니다:
nanomcp.server는 MCP 서버로서 stdio를 통해 JSON-RPC를 송수신합니다.nanomcp.cli는 MCP 클라이언트/호스트로서 서버를 시작하고initialize,tools/list,tools/call을 수행합니다.chat명령어는 OpenAI Chat Completions를 호출합니다. 모델이 function/tool call을 반환하면, CLI는 이를 MCPtools/call로 변환하고, 도구 결과를 다시 모델에 보내 최종 답변을 생성합니다.
MCP와 function call의 관계
한 문장으로 요약하자면: function call은 "모델이 당신의 애플리케이션에 어떤 함수를 호출하고 싶은지 알려주는" 모델 API 기능이며, MCP는 "당신의 애플리케이션이 통합된 프로토콜을 사용하여 외부 도구/컨텍스트 서비스를 발견하고 호출하는 방법"을 정의하는 연결 프로토콜입니다.
더 구체적으로 설명하면:
Function/tool calling은
LLM API <-> 당신의 애플리케이션사이에서 발생합니다. 모델은 실제로 함수를 실행하지 않으며,{"name":"get_weather","arguments":{...}}와 같은 호출 의도만 반환합니다.MCP는
당신의 애플리케이션 <-> MCP 서버사이에서 발생합니다. MCP 서버는tools/list및tools/call과 같은 도구 목록과 실행 진입점을 노출합니다.호스트/클라이언트는 중개자입니다. 먼저 MCP 서버에서 도구 스키마를 가져와 모델 API의 도구로 변환합니다. 모델이 도구를 선택하면 호스트/클라이언트는 MCP 서버를 호출합니다.
본 프로젝트의 링크는 다음과 같습니다:
用户问题
-> nanomcp.cli
-> OpenAI Chat Completions tools=function schemas
<- 模型返回 tool_calls
-> nanomcp.cli 把 tool_call 映射为 MCP tools/call
-> nanomcp.server 执行 get_weather 或 find_files
<- MCP tool result
-> nanomcp.cli 把结果发回模型
<- 模型最终回答따라서 이들은 같은 계층이 아닙니다:
Function call: 模型 API 的工具选择/参数生成机制
MCP: 应用连接工具服务器的标准协议Related MCP server: MCP Server Demo
파일 구조
nanomcp/
nanomcp/
cli.py # MCP client + model caller
server.py # hand-written MCP server over stdio
tests/
test_protocol.py
pyproject.toml
README.md모델 호출 없이 MCP 직접 실행
프로젝트 디렉토리에서 다음을 실행하세요:
cd ~/Desktop/nanomcp
python3 -m nanomcp.cli list-tools날씨 도구 직접 호출:
python3 -m nanomcp.cli call get_weather '{"location":"Shanghai","unit":"celsius"}'현재 날짜 및 시간 도구 직접 호출:
python3 -m nanomcp.cli call get_current_datetime '{"timezone":"Asia/Shanghai"}'파일 찾기 도구 직접 호출:
python3 -m nanomcp.cli call find_files '{"query":"*.pdf","max_results":5}'기본적으로 ~/Desktop만 검색합니다. 검색 루트 디렉토리를 일시적으로 확장하거나 축소할 수 있습니다:
NANOMCP_FILE_ROOT=~/Desktop/nanomcp python3 -m nanomcp.cli call find_files '{"query":"*.py"}'전체 모델 + MCP 링크 실행
OpenAI API 키가 필요합니다. 여기서는 OpenAI Python SDK를 사용하지 않고 표준 라이브러리 urllib을 사용하여 HTTP를 직접 전송합니다.
로컬 설정을 .env에 작성하는 것을 권장합니다:
cd ~/Desktop/nanomcp
cp .envtemplate .env그런 다음 .env를 편집하세요:
OPENAI_API_KEY=你的 key
OPENAI_BASE_URL=https://api.openai.com/v1
NANOMCP_MODEL=gpt-4.1-mini
NANOMCP_TIMEZONE=Asia/Shanghai.env는 CLI에 의해 자동으로 읽히며, 이미 .gitignore에 포함되어 있습니다.
cd ~/Desktop/nanomcp
python3 -m nanomcp.cli chat "上海今天天气怎么样?顺便帮我找桌面上的 PDF 文件"기본 모델은 gpt-4.1-mini입니다. 변경할 수 있습니다:
NANOMCP_MODEL=gpt-5-mini python3 -m nanomcp.cli chat "找一下这个项目里的 py 文件"OpenAI 호환 게이트웨이를 사용하는 경우:
OPENAI_BASE_URL=http://localhost:8000/v1 python3 -m nanomcp.cli chat "上海天气怎么样?"로컬 설정 및 MCP 서버에 대한 가벼운 점검:
python3 -m nanomcp.cli doctor문제 해결
chat 출력에 OpenAI API quota is exhausted (429 insufficient_quota)가 표시되면, 모델 API가 요청을 거부했음을 의미합니다. 현재 OPENAI_API_KEY가 속한 프로젝트에 사용 가능한 할당량이 없거나 결제가 활성화되지 않았습니다. 이는 모델이 tool call을 반환하기 전에 요청이 거부된 것이므로 MCP 서버 실패가 아닙니다.
점검 순서:
python3 -m nanomcp.cli doctor
echo "$OPENAI_API_KEY"
cat .env
python3 -m nanomcp.cli call get_weather '{"location":"Shanghai"}'
OPENAI_BASE_URL=http://localhost:8000/v1 python3 -m nanomcp.cli chat "上海天气怎么样?"첫 번째 명령어는 유효한 설정, 셸이
.env를 덮어쓰는지 여부, MCP 서버가 도구를 나열할 수 있는지 여부를 마스킹하여 표시합니다.두 번째 명령어는 셸에 키가 설정되어 있는지 확인합니다.
세 번째 명령어는
.env의 로컬 설정을 확인합니다.네 번째 명령어는 모델 API에 의존하지 않고 로컬 MCP 링크가 정상인지 확인합니다.
다섯 번째 명령어는 OpenAI 호환 게이트웨이로 전환하는 방법을 보여줍니다.
여전히 OpenAI 공식 API를 사용하는 경우, 할당량이 있는 키/프로젝트로 교체하거나 결제 및 모델 권한을 확인해야 합니다.
실제 날씨 사용(선택 사항)
기본 날씨는 네트워크나 타사 키가 없을 때 프로토콜 링크를 학습하기 편리하도록 결정론적 데모 데이터를 사용합니다. 실제 조회를 시도하려면:
NANOMCP_LIVE_WEATHER=1 python3 -m nanomcp.cli call get_weather '{"location":"Shanghai"}'실제 날씨는 https://wttr.in을 사용하며, 실패 시 자동으로 데모 데이터로 대체됩니다.
테스트
cd ~/Desktop/nanomcp
python3 -m unittest discover -s tests테스트 범위:
MCP
initializeMCP
tools/listMCP
tools/call get_weatherMCP
tools/call find_filesMCP
tools/call get_current_datetime
주요 관찰 사항
nanomcp/cli.py의 openai_tools_from_mcp()를 확인하세요: MCP 도구 스키마를 OpenAI 함수 도구 스키마로 변환합니다.
run_chat()을 확인하세요: 모델의 tool_calls를 수신한 후 mcp.call_tool()을 호출합니다. 이것이 MCP와 function call의 연결 지점입니다.
nanomcp/server.py의 main()을 확인하세요: stdin을 읽고 stdout에 쓰기만 하며, 각 줄은 JSON-RPC입니다. 서버는 OpenAI를 알지 못하며 모델에 직접 접근하지도 않습니다.
Available Tools
3 toolsfind_filesLocal file finderB
Find local files by name under the allowed root. The default root is ~/Desktop. Set NANOMCP_FILE_ROOT to change it.
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | Filename substring or glob pattern, such as *.pdf. | |
| root | No | Optional subdirectory under NANOMCP_FILE_ROOT. | |
| max_results | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries full burden. It mentions the root directory and default, but it does not disclose important behaviors such as case sensitivity, recursion depth, glob pattern handling, permissions, or the structure of returned results.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is extremely concise: two sentences. The first sentence states purpose and scope, the second provides configuration info. Every sentence adds value with no redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given that there is no output schema, the description should hint at return format or behavior. It does not mention what is returned (file paths, metadata), sorting, recursion, or error handling. The tool is simple but the agent may need more context for correct invocation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema already describes two of three parameters (query and root). The description adds context about the root default and environment variable configuration, but does not enhance understanding of max_results or clarify glob pattern syntax beyond what the schema provides.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's function: 'Find local files by name under the allowed root.' It specifies the scope (local files) and the constraint (under a root). The siblings are unrelated (datetime and weather), so there is no ambiguity.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no explicit guidance on when to use this tool versus alternatives. It does not mention when not to use it or any prerequisites. Given that siblings are unrelated, implicit guidance is minimal.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_current_datetimeCurrent date and timeA
Get the current date, time, and weekday. Use this for questions about today, current time, current date, or weekday.
| Name | Required | Description | Default |
|---|---|---|---|
| timezone | No | IANA timezone name, such as Asia/Shanghai or America/New_York. Defaults to NANOMCP_TIMEZONE or Asia/Shanghai. | Asia/Shanghai |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations exist, so the description carries full burden. It adequately describes the output (date, time, weekday) and timezone parameter. However, it does not mention that the operation is read-only, instantaneous, or any potential dependencies, leaving some behavioral details implicit.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two sentences, concise and front-loaded with the core function. Every sentence serves a purpose without redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity (one optional parameter, no output schema), the description fully covers what the tool does, its possible output, and appropriate use cases. No gaps remain.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
With full schema coverage (100%), the description adds no new parameter details beyond the schema. The schema already describes the timezone parameter well, so the description provides minimal added value, meeting the baseline of 3.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool retrieves current date, time, and weekday. It explicitly lists use cases like 'today, current time, current date, or weekday', and siblings are unrelated, making purpose unambiguous.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description directly states when to use the tool ('for questions about today, current time, current date, or weekday'). It does not provide exclusions or alternatives, but given the simplicity and distinct siblings, this is sufficient.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_weatherWeather lookupA
Get current weather for a city. By default this returns deterministic demo data. Set NANOMCP_LIVE_WEATHER=1 to try wttr.in.
| Name | Required | Description | Default |
|---|---|---|---|
| location | Yes | City or place name, for example Shanghai. | |
| unit | No | Temperature unit. | celsius |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations exist, so the description carries the burden. It discloses the demo/live behavior and environment variable, but lacks details on return format, error handling, or external API dependencies.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two sentences efficiently define purpose and critical behavioral context. No superfluous text.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple weather tool, the description covers core purpose and key behavioral nuance. However, it omits return value structure or typical properties, which would help the agent understand the output.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Input schema covers 100% of parameters with descriptions. The description adds no additional parameter meaning beyond what the schema provides, meeting baseline.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states 'Get current weather for a city,' using a specific verb and resource, and distinguishes from siblings like find_files and get_current_datetime.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
It explains the default demo mode and how to switch to live data, providing context for when to expect real or synthetic data. No explicit alternatives or exclusions but sufficient for this tool.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v0.1.0- First observed
find_files - First observed
get_current_datetime - First observed
get_weather
TDQS
Scored across 3 tools
Each tool has a clear, distinct purpose: file search, datetime, and weather. No overlap or ambiguity.
All tool names follow the verb_noun snake_case pattern consistently: find_files, get_current_datetime, get_weather.
Three tools is small but appropriate for a 'nano' server intended as a minimal utility collection. Not too few given its scope.
The tools cover only three disparate areas with no clear domain. As a general utility set, common operations like calculations or text processing are missing, but it may be intentionally limited.
Maintenance
Related MCP Connectors
Nifty's MCP server — exposes tasks, projects, messages, and files as tools for AI agents.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Related MCP Servers
- AlicenseBqualityDmaintenanceA demonstration MCP server that provides example tools for weather queries, time retrieval, and request handling, along with advice prompts. Supports both HTTP and stdio modes for testing MCP client integrations.4MIT
- AlicenseNot gradedqualityDmaintenanceA minimal Model Context Protocol server demo that exposes tools through HTTP API, including greeting, weather lookup, and HTTP request capabilities. Demonstrates MCP server implementation with stdio communication and HTTP gateway functionality.7 npmISC
- FlicenseNot gradedqualityDmaintenanceA minimal MCP server demo in Python that exposes five tools for arithmetic and a simulated long-running process.-
- FlicenseNot gradedqualityDmaintenanceA basic MCP server demonstrating tool registration and SSE transport, enabling AI clients to call greeting, arithmetic, and time tools.-