everyonetools-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 EveryoneTools
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ # Keep the sdist to what users need: the package, LICENSE and the PyPI readme (PYPI_README.md).
2
+ # README.md is the repository developer guide; tests need the repo conftest and fixtures.
3
+ exclude README.md
4
+ prune tests
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: everyonetools-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for the EveryoneTools developer API (/v1): discover and run EveryoneTools tools from MCP clients with your API key.
5
+ Author: EveryoneTools
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://everyonetools.com/developers/mcp
8
+ Project-URL: Documentation, https://everyonetools.com/developers/docs
9
+ Keywords: mcp,model-context-protocol,everyonetools,api,ai-agent
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: mcp<3,>=2.3.0
22
+ Requires-Dist: httpx<1,>=0.28
23
+ Dynamic: license-file
24
+
25
+ # everyonetools-mcp
26
+
27
+ MCP server for the [EveryoneTools developer API](https://everyonetools.com/developers). It lets MCP clients
28
+ (Claude Code, Claude Desktop, Cursor and other MCP-compatible tools) discover and run EveryoneTools tools with
29
+ your API key. Validation, credits and idempotency all happen in the API (`/v1`); this package is a thin wrapper
30
+ and contains no calculation logic.
31
+
32
+ 에브리원툴즈 개발자 API의 MCP 서버입니다. MCP 클라이언트(Claude Code, Claude Desktop, Cursor 등)가 내 API 키로
33
+ 에브리원툴즈 도구를 찾아 실행할 수 있게 합니다. 검증·크레딧·중복 차감 방지는 모두 API(`/v1`)가 처리합니다.
34
+
35
+ ## Requirements
36
+
37
+ - Python 3.11 or later
38
+ - An EveryoneTools API key — sign in at <https://everyonetools.com/developers/dashboard> and create a key
39
+ (the free plan includes 500 credits a month)
40
+
41
+ ## Run
42
+
43
+ ```bash
44
+ uvx everyonetools-mcp # with uv
45
+ pipx run everyonetools-mcp # or with pipx
46
+ ```
47
+
48
+ The server speaks MCP over stdio — your MCP client starts it. Pass the API key **only as an environment
49
+ variable**, never as a command argument, and never paste it into a shared project file or a chat.
50
+
51
+ ```bash
52
+ export EVERYONETOOLS_API_KEY="evt_live_..." # macOS / Linux
53
+ $env:EVERYONETOOLS_API_KEY = "evt_live_..." # Windows PowerShell
54
+ ```
55
+
56
+ `everyonetools-mcp --version` prints the installed version.
57
+
58
+ ## Connect a client
59
+
60
+ Claude Code — project file `.mcp.json` (the key stays in your environment, not in the file):
61
+
62
+ ```json
63
+ {
64
+ "mcpServers": {
65
+ "everyonetools": {
66
+ "command": "uvx",
67
+ "args": ["everyonetools-mcp"],
68
+ "env": { "EVERYONETOOLS_API_KEY": "${EVERYONETOOLS_API_KEY}" }
69
+ }
70
+ }
71
+ }
72
+ ```
73
+
74
+ Other clients use the same command (`uvx everyonetools-mcp`) and the same environment variable. If a client can
75
+ only take the key in its own settings, keep that settings file private and out of version control.
76
+
77
+ ## Tools
78
+
79
+ - The tools the API publishes for MCP — currently `calc_loan`, `calc_vat` and `text_count` (1 credit per
80
+ successful call). Names are the API tool IDs with `.` replaced by `_`.
81
+ - `get_remaining_credits` — plan, balance and limits (not charged).
82
+ - `download_result_file` — download a file produced by a document tool, within its retention (not charged).
83
+ - Repeating the same tool with the same input within 24 hours is charged once
84
+ (`EVERYONETOOLS_MCP_AUTO_IDEMPOTENCY`, default `true`).
85
+
86
+ ## Environment variables
87
+
88
+ | Name | Default | Meaning |
89
+ |---|---|---|
90
+ | `EVERYONETOOLS_API_KEY` | (required) | Your API key |
91
+ | `EVERYONETOOLS_API_BASE` | `https://api.everyonetools.com` | API host |
92
+ | `EVERYONETOOLS_MCP_AUTO_IDEMPOTENCY` | `true` | Fold repeat calls with the same input into one charge |
93
+ | `EVERYONETOOLS_MCP_LANGUAGE` | `ko` | Language shown first in tool names and descriptions (`ko` or `en`) |
94
+
95
+ ## Links
96
+
97
+ - Developer portal: <https://everyonetools.com/developers>
98
+ - API documentation: <https://everyonetools.com/developers/docs>
99
+ - MCP guide: <https://everyonetools.com/developers/mcp>
100
+
101
+ License: MIT
@@ -0,0 +1,77 @@
1
+ # everyonetools-mcp
2
+
3
+ MCP server for the [EveryoneTools developer API](https://everyonetools.com/developers). It lets MCP clients
4
+ (Claude Code, Claude Desktop, Cursor and other MCP-compatible tools) discover and run EveryoneTools tools with
5
+ your API key. Validation, credits and idempotency all happen in the API (`/v1`); this package is a thin wrapper
6
+ and contains no calculation logic.
7
+
8
+ 에브리원툴즈 개발자 API의 MCP 서버입니다. MCP 클라이언트(Claude Code, Claude Desktop, Cursor 등)가 내 API 키로
9
+ 에브리원툴즈 도구를 찾아 실행할 수 있게 합니다. 검증·크레딧·중복 차감 방지는 모두 API(`/v1`)가 처리합니다.
10
+
11
+ ## Requirements
12
+
13
+ - Python 3.11 or later
14
+ - An EveryoneTools API key — sign in at <https://everyonetools.com/developers/dashboard> and create a key
15
+ (the free plan includes 500 credits a month)
16
+
17
+ ## Run
18
+
19
+ ```bash
20
+ uvx everyonetools-mcp # with uv
21
+ pipx run everyonetools-mcp # or with pipx
22
+ ```
23
+
24
+ The server speaks MCP over stdio — your MCP client starts it. Pass the API key **only as an environment
25
+ variable**, never as a command argument, and never paste it into a shared project file or a chat.
26
+
27
+ ```bash
28
+ export EVERYONETOOLS_API_KEY="evt_live_..." # macOS / Linux
29
+ $env:EVERYONETOOLS_API_KEY = "evt_live_..." # Windows PowerShell
30
+ ```
31
+
32
+ `everyonetools-mcp --version` prints the installed version.
33
+
34
+ ## Connect a client
35
+
36
+ Claude Code — project file `.mcp.json` (the key stays in your environment, not in the file):
37
+
38
+ ```json
39
+ {
40
+ "mcpServers": {
41
+ "everyonetools": {
42
+ "command": "uvx",
43
+ "args": ["everyonetools-mcp"],
44
+ "env": { "EVERYONETOOLS_API_KEY": "${EVERYONETOOLS_API_KEY}" }
45
+ }
46
+ }
47
+ }
48
+ ```
49
+
50
+ Other clients use the same command (`uvx everyonetools-mcp`) and the same environment variable. If a client can
51
+ only take the key in its own settings, keep that settings file private and out of version control.
52
+
53
+ ## Tools
54
+
55
+ - The tools the API publishes for MCP — currently `calc_loan`, `calc_vat` and `text_count` (1 credit per
56
+ successful call). Names are the API tool IDs with `.` replaced by `_`.
57
+ - `get_remaining_credits` — plan, balance and limits (not charged).
58
+ - `download_result_file` — download a file produced by a document tool, within its retention (not charged).
59
+ - Repeating the same tool with the same input within 24 hours is charged once
60
+ (`EVERYONETOOLS_MCP_AUTO_IDEMPOTENCY`, default `true`).
61
+
62
+ ## Environment variables
63
+
64
+ | Name | Default | Meaning |
65
+ |---|---|---|
66
+ | `EVERYONETOOLS_API_KEY` | (required) | Your API key |
67
+ | `EVERYONETOOLS_API_BASE` | `https://api.everyonetools.com` | API host |
68
+ | `EVERYONETOOLS_MCP_AUTO_IDEMPOTENCY` | `true` | Fold repeat calls with the same input into one charge |
69
+ | `EVERYONETOOLS_MCP_LANGUAGE` | `ko` | Language shown first in tool names and descriptions (`ko` or `en`) |
70
+
71
+ ## Links
72
+
73
+ - Developer portal: <https://everyonetools.com/developers>
74
+ - API documentation: <https://everyonetools.com/developers/docs>
75
+ - MCP guide: <https://everyonetools.com/developers/mcp>
76
+
77
+ License: MIT
@@ -0,0 +1,3 @@
1
+ """EveryoneTools MCP 서버 — 개발자 API(`/v1`)의 래퍼(Phase 6). 사용법은 패키지 README."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,131 @@
1
+ """실행 진입점 — `python -m everyonetools_mcp [--transport stdio|http] …`
2
+
3
+ stdio(기본): MCP 클라이언트(Claude Code 등)가 이 프로세스를 띄운다. API 키는 환경 변수 `EVERYONETOOLS_API_KEY`(필수)로 받는다 — 인자·로그에 쓰지 않는다.
4
+ http(원격, Streamable HTTP): `EVERYONETOOLS_MCP_REMOTE_ENABLED=true` 일 때만 뜬다(01-architecture 의 `MCP_REMOTE_ENABLED` 플래그에 해당). 요청마다
5
+ `Authorization: Bearer <API 키>` 를 요구한다 — 공식 인가 규격(OAuth 2.1 · RFC 9728)이 아니라 **클라이언트가 고정 헤더를 보낼 수 있을 때만** 쓰는 방식이다
6
+ (`docs/api-platform/07-mcp-compatibility.md`). 로컬 밖에서 띄우려면 허용 호스트·오리진을 환경 변수로 적는다(DNS 리바인딩 방어).
7
+
8
+ 환경 변수: EVERYONETOOLS_API_BASE(기본 운영 API 호스트) · EVERYONETOOLS_API_KEY · EVERYONETOOLS_MCP_AUTO_IDEMPOTENCY(기본 true) · EVERYONETOOLS_MCP_LANGUAGE(ko|en)
9
+ · EVERYONETOOLS_MCP_REMOTE_ENABLED · EVERYONETOOLS_MCP_ALLOWED_HOSTS · EVERYONETOOLS_MCP_ALLOWED_ORIGINS(쉼표 구분)
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import logging
15
+ import os
16
+ import sys
17
+
18
+ import anyio
19
+
20
+ from . import __version__
21
+ from .server import Settings, create_server
22
+ from .v1_client import DEFAULT_API_BASE, looks_like_api_key
23
+
24
+
25
+ def _env_flag(name: str, default: bool) -> bool:
26
+ value = os.environ.get(name)
27
+ if value is None or value.strip() == "":
28
+ return default
29
+ return value.strip().lower() in ("1", "true", "yes", "on")
30
+
31
+
32
+ def _env_list(name: str) -> list[str]:
33
+ return [item.strip() for item in (os.environ.get(name) or "").split(",") if item.strip()]
34
+
35
+
36
+ def settings_from_env(*, require_key: bool) -> Settings:
37
+ api_key = (os.environ.get("EVERYONETOOLS_API_KEY") or "").strip() or None
38
+ if require_key and not looks_like_api_key(api_key):
39
+ # 사용자에게 보이는 문구는 영어를 앞에 두고 ASCII 문장 부호만 쓴다 — 로캘 인코딩(cp949 등)의 파이프로 나가도 깨지지 않게
40
+ raise SystemExit(
41
+ "EVERYONETOOLS_API_KEY is missing or malformed (evt_...). Pass the key from the developer portal as an environment variable. / "
42
+ "EVERYONETOOLS_API_KEY 가 없거나 형식이 아닙니다(evt_...). 개발자 포털에서 발급한 키를 환경 변수로 넘기세요."
43
+ )
44
+ language = (os.environ.get("EVERYONETOOLS_MCP_LANGUAGE") or "ko").strip().lower()
45
+ return Settings(
46
+ api_base=(os.environ.get("EVERYONETOOLS_API_BASE") or DEFAULT_API_BASE).strip().rstrip("/"),
47
+ api_key=api_key if require_key else None,
48
+ auto_idempotency=_env_flag("EVERYONETOOLS_MCP_AUTO_IDEMPOTENCY", True),
49
+ language="en" if language == "en" else "ko",
50
+ )
51
+
52
+
53
+ async def _run_stdio(settings: Settings) -> None:
54
+ from mcp.server.stdio import stdio_server
55
+
56
+ app = create_server(settings)
57
+ try:
58
+ async with stdio_server() as (read_stream, write_stream):
59
+ await app.server.run(read_stream, write_stream, app.server.create_initialization_options())
60
+ finally:
61
+ await app.client.aclose()
62
+
63
+
64
+ def build_http_app(settings: Settings, *, host: str, path: str, allowed_hosts: list[str], allowed_origins: list[str]):
65
+ """원격 모드의 ASGI 앱 — SDK 의 Streamable HTTP 앱(무상태·JSON 응답) 앞에 Bearer 검사(형식만 — 진짜 검증은 /v1)를 둔다."""
66
+ from mcp.server.transport_security import TransportSecuritySettings
67
+
68
+ from .http_auth import BearerKeyMiddleware
69
+
70
+ app = create_server(settings)
71
+ security = None
72
+ if allowed_hosts or allowed_origins:
73
+ security = TransportSecuritySettings(enable_dns_rebinding_protection=True, allowed_hosts=allowed_hosts, allowed_origins=allowed_origins)
74
+ starlette_app = app.server.streamable_http_app(streamable_http_path=path, json_response=True, stateless_http=True, transport_security=security, host=host)
75
+ return BearerKeyMiddleware(starlette_app, protected_path=path), app
76
+
77
+
78
+ def _tolerate_unencodable_output() -> None:
79
+ """콘솔·파이프의 인코딩(한국어 Windows 의 cp949 등)이 못 쓰는 글자를 ? 로 바꿔 출력이 예외로 끊기지 않게 한다.
80
+
81
+ stdio 모드의 MCP 메시지는 SDK 가 sys.stdout.buffer 위에 따로 만든 UTF-8 통로로 나가므로 영향이 없다 — 바뀌는 것은
82
+ 도움말·종료 문구·로그(stderr)뿐이다. 0.1.0 준비 중 cp949 파이프에서 --help 가 UnicodeEncodeError 로 끊긴 것을 보고 넣었다.
83
+ """
84
+ for stream in (sys.stdout, sys.stderr):
85
+ reconfigure = getattr(stream, "reconfigure", None)
86
+ if reconfigure is None:
87
+ continue
88
+ try:
89
+ reconfigure(errors="replace")
90
+ except (ValueError, OSError):
91
+ pass
92
+
93
+
94
+ def main(argv: list[str] | None = None) -> int:
95
+ _tolerate_unencodable_output()
96
+ parser = argparse.ArgumentParser(
97
+ prog="everyonetools-mcp",
98
+ description="MCP server for the EveryoneTools developer API (/v1). Tools, validation and credits are handled by the API.",
99
+ )
100
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
101
+ parser.add_argument("--transport", choices=("stdio", "http"), default="stdio")
102
+ parser.add_argument("--host", default="127.0.0.1")
103
+ parser.add_argument("--port", type=int, default=8765)
104
+ parser.add_argument("--path", default="/mcp")
105
+ parser.add_argument("--log-level", default="INFO")
106
+ args = parser.parse_args(argv)
107
+ logging.basicConfig(level=getattr(logging, str(args.log_level).upper(), logging.INFO), stream=sys.stderr, format="%(asctime)s %(levelname)s %(name)s %(message)s")
108
+ for noisy in ("httpx", "httpcore"): # HTTP 클라이언트의 요청 줄(주소 — 파일 ID 가 들어간다)은 남기지 않는다. 우리 로그는 도구 이름·오류 코드·요청 ID 만
109
+ logging.getLogger(noisy).setLevel(logging.WARNING)
110
+
111
+ if args.transport == "stdio":
112
+ settings = settings_from_env(require_key=True)
113
+ anyio.run(_run_stdio, settings)
114
+ return 0
115
+
116
+ if not _env_flag("EVERYONETOOLS_MCP_REMOTE_ENABLED", False):
117
+ raise SystemExit(
118
+ "Remote (HTTP) mode starts only when EVERYONETOOLS_MCP_REMOTE_ENABLED=true (off by default). / "
119
+ "원격(HTTP) 모드는 EVERYONETOOLS_MCP_REMOTE_ENABLED=true 일 때만 뜹니다(기본 꺼짐)."
120
+ )
121
+ import uvicorn
122
+
123
+ settings = settings_from_env(require_key=False)
124
+ asgi_app, _wrapper = build_http_app(settings, host=args.host, path=args.path, allowed_hosts=_env_list("EVERYONETOOLS_MCP_ALLOWED_HOSTS"),
125
+ allowed_origins=_env_list("EVERYONETOOLS_MCP_ALLOWED_ORIGINS"))
126
+ uvicorn.run(asgi_app, host=args.host, port=args.port, log_level=str(args.log_level).lower())
127
+ return 0
128
+
129
+
130
+ if __name__ == "__main__":
131
+ sys.exit(main())
@@ -0,0 +1,59 @@
1
+ """원격(Streamable HTTP) 모드의 Bearer 검사 — ASGI 미들웨어.
2
+
3
+ MCP 엔드포인트로 오는 요청에 `Authorization: Bearer <API 키>` 가 있고 키 모양(evt_…)이면 통과시킨다. 키의 진짜 검증(존재·스코프·조직)은 `/v1` 이 요청마다 한다 —
4
+ 여기서는 키 없는 요청이 MCP 처리까지 가지 않게만 막는다(401 + `WWW-Authenticate: Bearer`). 공식 인가 규격(OAuth 2.1 · RFC 9728 보호 자원 메타데이터)은
5
+ 구현하지 않았다 — 인가 서버가 없기 때문이다. 그래서 `/.well-known/oauth-protected-resource` 도 내지 않는다(없는 인가 서버를 가리키면 클라이언트가 헛돈다).
6
+ 키 원문은 로그에 쓰지 않는다.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from typing import Any, Awaitable, Callable
12
+
13
+ from .v1_client import looks_like_api_key
14
+
15
+ ASGIApp = Callable[[dict[str, Any], Callable[[], Awaitable[dict[str, Any]]], Callable[[dict[str, Any]], Awaitable[None]]], Awaitable[None]]
16
+
17
+
18
+ class BearerKeyMiddleware:
19
+ def __init__(self, app: ASGIApp, *, protected_path: str = "/mcp"):
20
+ self.app = app
21
+ self.protected_path = protected_path.rstrip("/") or "/"
22
+
23
+ async def __call__(self, scope: dict[str, Any], receive: Callable[[], Awaitable[dict[str, Any]]], send: Callable[[dict[str, Any]], Awaitable[None]]) -> None:
24
+ if scope.get("type") != "http":
25
+ await self.app(scope, receive, send)
26
+ return
27
+ path = str(scope.get("path") or "").rstrip("/") or "/"
28
+ if path == self.protected_path or path.startswith(self.protected_path + "/"):
29
+ token = _bearer_token(scope)
30
+ if not looks_like_api_key(token):
31
+ await _unauthorized(send)
32
+ return
33
+ await self.app(scope, receive, send)
34
+
35
+
36
+ def _bearer_token(scope: dict[str, Any]) -> str | None:
37
+ for name, value in scope.get("headers") or []:
38
+ if name.lower() == b"authorization":
39
+ header = value.decode("latin-1", "replace")
40
+ scheme, _, token = header.partition(" ")
41
+ if scheme.lower() == "bearer":
42
+ return token.strip()
43
+ return None
44
+ return None
45
+
46
+
47
+ async def _unauthorized(send: Callable[[dict[str, Any]], Awaitable[None]]) -> None:
48
+ body = json.dumps({"error": {"code": "api_key_missing", "message": "Authorization: Bearer <API 키> 가 필요합니다."}}).encode("utf-8")
49
+ await send({
50
+ "type": "http.response.start",
51
+ "status": 401,
52
+ "headers": [
53
+ (b"content-type", b"application/json"),
54
+ (b"content-length", str(len(body)).encode("ascii")),
55
+ (b"www-authenticate", b'Bearer realm="everyonetools-mcp", error="invalid_token"'),
56
+ (b"cache-control", b"no-store"),
57
+ ],
58
+ })
59
+ await send({"type": "http.response.body", "body": body})
@@ -0,0 +1,283 @@
1
+ """EveryoneTools MCP 서버 — 공통 도구 레지스트리의 **래퍼**(Phase 6, 2026-11-12, `docs/api-platform/07-mcp-compatibility.md`).
2
+
3
+ - 도구 정의는 `/v1/tools`·`/v1/tools/{id}` 에서 받아 그대로 내보낸다(이름의 `.` 만 `_` 로 — `calc.loan` → `calc_loan`). 계산·검증·과금은 전부 `/v1` 이 한다.
4
+ 여기에 도구 로직을 복사하지 않는다(01-architecture §1). 레지스트리에 MCP 채널 도구가 늘면 재시작만으로 여기도 늘어난다.
5
+ - 호출마다 `Idempotency-Key` 를 보낸다. 호출자가 `idempotency_key` 를 주지 않으면 **같은 도구·같은 입력의 지문**(`mcp-<sha256 40자>`)을 쓴다 —
6
+ AI 에이전트의 재시도·반복 호출이 24시간 안에서는 저장된 응답을 받고 다시 차감되지 않는다(REST 와 같은 규칙, 키만 자동). 끌 수 있다(`auto_idempotency=False`).
7
+ - 키: stdio 는 프로세스 하나의 키(`Settings.api_key`), 원격(HTTP)은 요청의 `Authorization: Bearer` 를 쓴다(`ctx.request`). 키 원문은 결과·로그·오류에 쓰지 않는다.
8
+ - 결과: `structured_content` 에 `{tool_id, request_id, replayed, credits, output}`, `content` 에 같은 내용의 JSON 텍스트. `/v1` 의 거절은 `is_error=True` 와
9
+ `{"error": {code, message, request_id, …}}` 로 돌려준다(프로토콜 오류가 아니라 도구 결과 — 모델이 읽고 바로잡을 수 있게).
10
+ - 파일 도구(`doc.quote`)의 결과 파일은 `download_result_file(file_id)` 가 받아 `EmbeddedResource`(base64) 로 돌려준다 — 다시 내려받아도 차감이 없다(REST 와 같다).
11
+ - 도구 설명에는 호출당 크레딧과 파일 생성 여부를 적어 에이전트가 비용을 알고 부르게 한다(브리프 §8.2).
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import hashlib
17
+ import json
18
+ import logging
19
+ import re
20
+ import secrets
21
+ import time
22
+ from dataclasses import dataclass, field
23
+ from typing import Any
24
+
25
+ import mcp.types as types
26
+ from mcp.server.lowlevel import Server
27
+
28
+ from .v1_client import FILE_ID_PATTERN, DownloadedFile, RunResult, V1Client, V1Error, looks_like_api_key
29
+
30
+ logger = logging.getLogger("everyonetools_mcp")
31
+
32
+ SERVER_NAME = "everyonetools"
33
+ SERVER_VERSION = "0.1.0"
34
+ INSTRUCTIONS = (
35
+ "에브리원툴즈(EveryoneTools) 개발자 API 의 도구를 호출합니다. 각 도구는 호출당 설명에 적힌 크레딧을 조직의 잔액에서 씁니다(성공한 호출만). "
36
+ "같은 도구·같은 입력을 24시간 안에 다시 부르면 저장된 결과를 돌려주고 다시 차감하지 않습니다(idempotency_key 로 직접 정할 수도 있습니다). "
37
+ "잔액·한도는 get_remaining_credits, 문서 도구의 결과 파일은 download_result_file 로 받습니다."
38
+ )
39
+ TOOLS_CACHE_SECONDS = 300
40
+ FORCED_REFRESH_MIN_SECONDS = 30 # 모르는 도구 이름이 연달아 와도 목록을 이 간격보다 자주 다시 읽지 않는다
41
+ IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._-]{1,128}$")
42
+ AUTO_IDEMPOTENCY_PREFIX = "mcp-"
43
+ HELPER_CREDITS = "get_remaining_credits"
44
+ HELPER_DOWNLOAD = "download_result_file"
45
+ MAX_DOWNLOAD_BYTES = 8 * 1024 * 1024 # base64 로 11MB 남짓 — Claude Code 의 HTTP 응답 상한(16MiB) 아래
46
+ TEXT_LIMIT = 40_000 # content 텍스트 상한(결과 JSON) — 그 이상은 structured_content 만 온전하다
47
+
48
+
49
+ @dataclass
50
+ class Settings:
51
+ api_base: str
52
+ api_key: str | None = None # stdio 모드의 키 — 원격 모드는 요청 헤더
53
+ auto_idempotency: bool = True
54
+ language: str = "ko" # 도구 이름·설명에서 앞에 둘 언어(ko | en) — 둘 다 넣는다
55
+
56
+
57
+ @dataclass
58
+ class _ToolsCache:
59
+ fetched_at: float = 0.0
60
+ tools: list[types.Tool] = field(default_factory=list)
61
+ id_by_name: dict[str, str] = field(default_factory=dict) # MCP 이름 → 레지스트리 도구 ID
62
+ detail_by_id: dict[str, dict[str, Any]] = field(default_factory=dict)
63
+
64
+
65
+ def mcp_tool_name(tool_id: str) -> str:
66
+ """레지스트리 도구 ID → MCP 도구 이름. 점은 밑줄로(클라이언트가 `mcp__<서버>__<도구>` 로 합치므로 점을 피한다)."""
67
+ return tool_id.replace(".", "_")
68
+
69
+
70
+ def auto_idempotency_key(tool_id: str, tool_version: str | None, tool_input: dict[str, Any]) -> str:
71
+ """같은 도구(버전 포함)·같은 입력의 지문 — 서버의 요청 지문도 (도구, 버전, 입력)이라 버전이 바뀌면 키도 바뀌어야 409(같은 키·다른 본문)가 나지 않는다."""
72
+ material = json.dumps([tool_id, tool_version or "", tool_input], sort_keys=True, separators=(",", ":"), ensure_ascii=False)
73
+ return AUTO_IDEMPOTENCY_PREFIX + hashlib.sha256(material.encode("utf-8")).hexdigest()[:40]
74
+
75
+
76
+ def _pick(mapping: Any, language: str) -> str:
77
+ """{ko, en} 표시 문자열에서 두 언어를 '한국어 — English' 로 합친다(둘 다 있을 때)."""
78
+ if not isinstance(mapping, dict):
79
+ return str(mapping or "")
80
+ first = str(mapping.get(language) or "")
81
+ other = str(mapping.get("en" if language == "ko" else "ko") or "")
82
+ if first and other and first != other:
83
+ return f"{first} — {other}"
84
+ return first or other
85
+
86
+
87
+ def build_tool(detail: dict[str, Any], *, language: str) -> types.Tool:
88
+ """`GET /v1/tools/{id}` 의 정의를 MCP Tool 로. 입력 스키마는 그대로 쓰고 `idempotency_key` 선택 속성만 더한다(서버로 보내기 전에 뗀다)."""
89
+ tool_id = str(detail["id"])
90
+ schema = dict(detail.get("input_schema") or {"type": "object"})
91
+ properties = dict(schema.get("properties") or {})
92
+ properties["idempotency_key"] = {
93
+ "type": "string",
94
+ "pattern": IDEMPOTENCY_KEY_PATTERN.pattern,
95
+ "description": "선택 — 재시도를 한 번으로 묶는 키(영숫자·점·밑줄·하이픈 1~128자). 비우면 같은 도구·같은 입력의 지문을 쓴다",
96
+ }
97
+ schema["properties"] = properties
98
+ cost = detail.get("credit_cost")
99
+ cost_class = detail.get("cost_class")
100
+ unit = detail.get("cost_unit") or "call"
101
+ if cost_class == "metered":
102
+ cost_line = f"크레딧: {cost}/{unit}(처리 단위 수 × 단가, 최대 {detail.get('max_units')}단위)"
103
+ else:
104
+ cost_line = f"크레딧: 호출 1회에 {cost}"
105
+ lines = [_pick(detail.get("description"), language), cost_line + " — 성공한 호출만 차감, 같은 입력의 24시간 안 재호출은 무차감."]
106
+ if detail.get("result_kind") == "file":
107
+ lines.append(f"결과는 파일(output.file)이다 — {HELPER_DOWNLOAD} 로 받는다(보관 {detail.get('file_ttl_hours')}시간, 재다운로드 무차감).")
108
+ return types.Tool(
109
+ name=mcp_tool_name(tool_id),
110
+ title=_pick(detail.get("name"), language),
111
+ description="\n".join(line for line in lines if line),
112
+ inputSchema=schema,
113
+ annotations=types.ToolAnnotations(
114
+ title=_pick(detail.get("name"), language), readOnlyHint=False, destructiveHint=False, idempotentHint=True, openWorldHint=False,
115
+ ),
116
+ )
117
+
118
+
119
+ def helper_tools() -> list[types.Tool]:
120
+ return [
121
+ types.Tool(
122
+ name=HELPER_CREDITS,
123
+ title="남은 크레딧·한도 — Remaining credits and limits",
124
+ description="조직의 플랜, 크레딧 잔액과 지급 기간, 일일 호출 상한, 처리율, 예산, 사용량 알림을 돌려준다. 차감 없음(읽기만).",
125
+ inputSchema={"type": "object", "properties": {}, "additionalProperties": False},
126
+ annotations=types.ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False),
127
+ ),
128
+ types.Tool(
129
+ name=HELPER_DOWNLOAD,
130
+ title="결과 파일 내려받기 — Download a result file",
131
+ description=(
132
+ "문서 도구가 만든 결과 파일(실행 결과 output.file.id)을 받는다. 같은 조직의 파일만, 보관 시간 안에서만. 차감 없음(파일당 횟수 상한만). "
133
+ "결과는 embedded resource(base64)와 파일 이름·종류·크기다."
134
+ ),
135
+ inputSchema={
136
+ "type": "object",
137
+ "properties": {"file_id": {"type": "string", "pattern": FILE_ID_PATTERN.pattern, "description": "실행 결과의 output.file.id(ULID 26자)"}},
138
+ "required": ["file_id"],
139
+ "additionalProperties": False,
140
+ },
141
+ annotations=types.ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False),
142
+ ),
143
+ ]
144
+
145
+
146
+ def _text(payload: Any) -> types.TextContent:
147
+ text = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
148
+ if len(text) > TEXT_LIMIT:
149
+ text = text[:TEXT_LIMIT] + "…(잘림 — 전체는 structuredContent)"
150
+ return types.TextContent(type="text", text=text)
151
+
152
+
153
+ def _error_result(error: V1Error) -> types.CallToolResult:
154
+ body = {"error": error.as_dict()}
155
+ return types.CallToolResult(content=[_text(body)], structuredContent=body, isError=True)
156
+
157
+
158
+ def _invalid(message: str, code: str = "invalid_arguments") -> types.CallToolResult:
159
+ body = {"error": {"code": code, "message": message}}
160
+ return types.CallToolResult(content=[_text(body)], structuredContent=body, isError=True)
161
+
162
+
163
+ class EveryoneToolsMCP:
164
+ """MCP 서버 한 개 — `/v1` 클라이언트와 도구 캐시를 들고 low-level Server 의 핸들러를 제공한다."""
165
+
166
+ def __init__(self, settings: Settings, client: V1Client):
167
+ self.settings = settings
168
+ self.client = client
169
+ self._cache = _ToolsCache()
170
+ self.server: Server[Any] = Server(
171
+ SERVER_NAME, version=SERVER_VERSION, title="EveryoneTools API", instructions=INSTRUCTIONS,
172
+ on_list_tools=self._on_list_tools, on_call_tool=self._on_call_tool,
173
+ )
174
+
175
+ # ── 키 ──
176
+ def _api_key(self, ctx: Any) -> str | None:
177
+ request = getattr(ctx, "request", None)
178
+ if request is not None: # 원격(HTTP) — 요청의 Bearer. 미들웨어가 형식을 먼저 거르지만 여기서도 확인한다
179
+ header = request.headers.get("authorization") or ""
180
+ scheme, _, token = header.partition(" ")
181
+ token = token.strip()
182
+ return token if scheme.lower() == "bearer" and looks_like_api_key(token) else None
183
+ return self.settings.api_key if looks_like_api_key(self.settings.api_key) else None
184
+
185
+ # ── 도구 목록 ──
186
+ async def _registry(self, api_key: str, *, force: bool = False) -> _ToolsCache:
187
+ now = time.monotonic()
188
+ age = now - self._cache.fetched_at
189
+ if self._cache.tools and age < (FORCED_REFRESH_MIN_SECONDS if force else TOOLS_CACHE_SECONDS):
190
+ return self._cache
191
+ summaries = await self.client.list_tools(api_key)
192
+ details: dict[str, dict[str, Any]] = {}
193
+ for summary in sorted(summaries, key=lambda item: str(item.get("id"))): # 결정적 순서(규격 SHOULD)
194
+ tool_id = str(summary.get("id") or "")
195
+ if not tool_id or "mcp" not in (summary.get("channels") or []):
196
+ continue
197
+ details[tool_id] = await self.client.get_tool(api_key, tool_id)
198
+ tools = [build_tool(detail, language=self.settings.language) for detail in details.values()] + helper_tools()
199
+ self._cache = _ToolsCache(fetched_at=now, tools=tools, id_by_name={mcp_tool_name(tool_id): tool_id for tool_id in details}, detail_by_id=details)
200
+ return self._cache
201
+
202
+ async def _on_list_tools(self, ctx: Any, params: types.PaginatedRequestParams | None) -> types.ListToolsResult:
203
+ api_key = self._api_key(ctx)
204
+ if api_key is None:
205
+ return types.ListToolsResult(tools=helper_tools()) # 키 없이는 레지스트리를 못 읽는다 — 도우미만(호출하면 키 오류로 안내)
206
+ try:
207
+ cache = await self._registry(api_key)
208
+ except V1Error as exc:
209
+ logger.warning("mcp: tools list unavailable code=%s", exc.code)
210
+ return types.ListToolsResult(tools=helper_tools())
211
+ return types.ListToolsResult(tools=list(cache.tools))
212
+
213
+ # ── 호출 ──
214
+ async def _on_call_tool(self, ctx: Any, params: types.CallToolRequestParams) -> types.CallToolResult:
215
+ name = params.name
216
+ arguments = dict(params.arguments or {})
217
+ api_key = self._api_key(ctx)
218
+ if api_key is None:
219
+ return _invalid("API 키가 없습니다 — stdio 는 EVERYONETOOLS_API_KEY, 원격은 Authorization: Bearer <키> 로 넘깁니다.", "api_key_missing")
220
+ try:
221
+ if name == HELPER_CREDITS:
222
+ return await self._credits(api_key)
223
+ if name == HELPER_DOWNLOAD:
224
+ return await self._download(api_key, arguments)
225
+ tool_id = self._cache.id_by_name.get(name)
226
+ if tool_id is None:
227
+ cache = await self._registry(api_key, force=True)
228
+ tool_id = cache.id_by_name.get(name)
229
+ if tool_id is None:
230
+ return _invalid(f"모르는 도구입니다: {name}", "unknown_tool")
231
+ return await self._run(api_key, tool_id, arguments)
232
+ except V1Error as exc:
233
+ logger.info("mcp: v1 refused tool=%s code=%s rid=%s", name, exc.code, exc.request_id)
234
+ return _error_result(exc)
235
+ except Exception as exc: # noqa: BLE001 — 예상 밖 오류도 프로토콜 오류(-32603)가 아니라 도구 결과로: 모델이 읽고 멈출 수 있게. 내부 정보는 싣지 않는다
236
+ logger.exception("mcp: unexpected failure tool=%s error=%s", name, type(exc).__name__)
237
+ return _invalid("도구를 호출하는 중 서버 내부 오류가 났습니다. 잠시 뒤 다시 시도해 주세요.", "internal_error")
238
+
239
+ async def _run(self, api_key: str, tool_id: str, arguments: dict[str, Any]) -> types.CallToolResult:
240
+ raw_key = arguments.pop("idempotency_key", None)
241
+ if raw_key is not None and (not isinstance(raw_key, str) or not IDEMPOTENCY_KEY_PATTERN.match(raw_key)):
242
+ return _invalid("idempotency_key 는 영숫자·점·밑줄·하이픈 1~128자입니다.")
243
+ if raw_key is None and not self.settings.auto_idempotency:
244
+ idempotency_key = AUTO_IDEMPOTENCY_PREFIX + secrets.token_hex(20) # 자동 묶기 끔 — 호출마다 새 키(시계 값은 해상도가 낮아 겹칠 수 있다)
245
+ else:
246
+ version = (self._cache.detail_by_id.get(tool_id) or {}).get("version")
247
+ idempotency_key = raw_key or auto_idempotency_key(tool_id, version, arguments)
248
+ result: RunResult = await self.client.run_tool(api_key, tool_id, arguments, idempotency_key=idempotency_key)
249
+ body = result.body
250
+ payload: dict[str, Any] = {
251
+ "tool_id": body.get("tool_id", tool_id), "tool_version": body.get("tool_version"), "request_id": result.request_id, "replayed": result.replayed,
252
+ "credits": body.get("credits"), "output": body.get("output"),
253
+ }
254
+ output_file = (body.get("output") or {}).get("file") if isinstance(body.get("output"), dict) else None
255
+ if isinstance(output_file, dict) and output_file.get("id"):
256
+ payload["file_hint"] = f"{HELPER_DOWNLOAD}(file_id=\"{output_file['id']}\")"
257
+ return types.CallToolResult(content=[_text(payload)], structuredContent=payload, isError=False)
258
+
259
+ async def _credits(self, api_key: str) -> types.CallToolResult:
260
+ limits = await self.client.limits(api_key)
261
+ payload = {key: limits.get(key) for key in ("plan", "credits", "daily_calls", "rate_limit", "daily_budget", "alerts", "organization") if key in limits}
262
+ payload["request_id"] = limits.get("request_id")
263
+ return types.CallToolResult(content=[_text(payload)], structuredContent=payload, isError=False)
264
+
265
+ async def _download(self, api_key: str, arguments: dict[str, Any]) -> types.CallToolResult:
266
+ file_id = arguments.get("file_id")
267
+ if not isinstance(file_id, str) or not FILE_ID_PATTERN.match(file_id):
268
+ return _invalid("file_id 는 실행 결과 output.file.id(ULID 26자)입니다.")
269
+ downloaded: DownloadedFile = await self.client.download_file(api_key, file_id)
270
+ if len(downloaded.content) > MAX_DOWNLOAD_BYTES:
271
+ return _invalid(f"파일이 너무 큽니다({len(downloaded.content)} bytes > {MAX_DOWNLOAD_BYTES}) — REST 의 /v1/files/{file_id} 로 받으세요.", "file_too_large")
272
+ summary = {"file_id": file_id, "filename": downloaded.filename, "content_type": downloaded.content_type, "size_bytes": len(downloaded.content)}
273
+ resource = types.EmbeddedResource(
274
+ type="resource",
275
+ resource=types.BlobResourceContents(
276
+ uri=f"everyonetools://files/{file_id}", mimeType=downloaded.content_type, blob=base64.b64encode(downloaded.content).decode("ascii"),
277
+ ),
278
+ )
279
+ return types.CallToolResult(content=[_text(summary), resource], structuredContent=summary, isError=False)
280
+
281
+
282
+ def create_server(settings: Settings, client: V1Client | None = None) -> EveryoneToolsMCP:
283
+ return EveryoneToolsMCP(settings, client or V1Client(settings.api_base))
@@ -0,0 +1,166 @@
1
+ """`/v1` 호출 래퍼 — MCP 서버는 도구 로직을 갖지 않는다. 도구 목록·스키마·실행·잔액·결과 파일 전부를 개발자용 REST API(`/v1`)에 그대로 묻는다
2
+ (같은 API 키 · 같은 스코프 · 같은 크레딧 장부 · 같은 멱등 규칙 — `docs/api-platform/01-architecture.md` §3.6).
3
+
4
+ - 인증은 요청마다 `Authorization: Bearer <API 키>` 다. 키 원문은 이 모듈 밖으로 내보내지 않고(로그·오류 메시지·결과에 없음) 호출자가 요청마다 넘긴다.
5
+ - 모든 요청에 `X-EveryoneTools-Channel: mcp` 를 붙인다 — 백엔드가 요청 기록의 채널을 `mcp` 로 적는다(크레딧 장부는 REST 와 같은 하나).
6
+ - 실행은 `Idempotency-Key` 를 반드시 붙인다(호출자가 만든다 — `server.py`): 같은 키의 재전송은 저장된 응답(`Idempotent-Replayed: true`)이고 다시 차감되지 않는다.
7
+ - 오류는 `/v1` 의 봉투 `{"error": {code, message, request_id, details, retry_after_seconds}}` 를 `V1Error` 로 옮긴다. 네트워크 오류는 code `network_error`.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass
13
+ from typing import Any
14
+ from urllib.parse import unquote
15
+
16
+ import httpx
17
+
18
+ DEFAULT_API_BASE = "https://api.everyonetools.com" # 운영 API 호스트(D1, 2026-11-13 — Firebase Hosting 사이트 everyonetools-api 가 /v1/** 를 백엔드로 넘긴다)
19
+ CHANNEL_HEADER = "X-EveryoneTools-Channel"
20
+ CHANNEL_MCP = "mcp"
21
+ IDEMPOTENCY_HEADER = "Idempotency-Key"
22
+ REPLAY_HEADER = "Idempotent-Replayed"
23
+ REQUEST_ID_HEADER = "X-Request-Id"
24
+ USER_AGENT = "everyonetools-mcp/0.1"
25
+ DEFAULT_TIMEOUT_SECONDS = 70.0 # 동기 도구 상한(백엔드 60초) + 여유
26
+ # 발급 형식만 거른다 — 진짜 검증은 서버가 한다. 백엔드는 `evt_live_` + secrets.token_urlsafe(32) 로 발급하므로 알파벳은 [A-Za-z0-9_-] 다
27
+ # (하이픈 포함 — 2026-11-12: 하이픈을 빼먹어 발급 키의 절반쯤이 시작 단계에서 거절됐다. 실제 Claude Code 연결에서 발견).
28
+ API_KEY_PATTERN = re.compile(r"evt_[A-Za-z0-9_-]{12,200}")
29
+ FILE_ID_PATTERN = re.compile(r"^[0-9A-HJKMNP-TV-Z]{26}$")
30
+ TOOL_ID_PATTERN = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
31
+
32
+
33
+ def looks_like_api_key(value: str | None) -> bool:
34
+ return bool(value) and API_KEY_PATTERN.fullmatch(value or "") is not None # fullmatch — 끝의 줄바꿈도 받지 않는다
35
+
36
+
37
+ class V1Error(Exception):
38
+ """`/v1` 가 거절했거나 닿지 못했다 — code 는 분기용(서버의 error.code 그대로), message 는 사람이 읽는 설명."""
39
+
40
+ def __init__(self, status: int, code: str, message: str, *, request_id: str | None = None, details: Any = None, retry_after_seconds: int | None = None):
41
+ super().__init__(f"{code}: {message}")
42
+ self.status = status
43
+ self.code = code
44
+ self.message = message
45
+ self.request_id = request_id
46
+ self.details = details
47
+ self.retry_after_seconds = retry_after_seconds
48
+
49
+ def as_dict(self) -> dict[str, Any]:
50
+ body: dict[str, Any] = {"code": self.code, "message": self.message, "http_status": self.status}
51
+ if self.request_id:
52
+ body["request_id"] = self.request_id
53
+ if self.details is not None:
54
+ body["details"] = self.details
55
+ if self.retry_after_seconds is not None:
56
+ body["retry_after_seconds"] = self.retry_after_seconds
57
+ return body
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class RunResult:
62
+ body: dict[str, Any] # RunResponse 그대로 — request_id · tool_id · tool_version · status · output · credits · duration_ms
63
+ replayed: bool # 같은 Idempotency-Key 의 저장된 응답이었다(차감 없음)
64
+ request_id: str
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class DownloadedFile:
69
+ content: bytes
70
+ content_type: str
71
+ filename: str
72
+
73
+
74
+ class V1Client:
75
+ """하나의 API 호스트에 대한 비동기 HTTP 클라이언트. 키는 요청마다 받는다(프로세스에 하나의 키가 있는 stdio 도, 요청마다 다른 키가 오는 원격 모드도 같은 코드)."""
76
+
77
+ def __init__(self, base_url: str = DEFAULT_API_BASE, *, timeout: float = DEFAULT_TIMEOUT_SECONDS, http_client: httpx.AsyncClient | None = None):
78
+ self.base_url = base_url.rstrip("/")
79
+ self._client = http_client or httpx.AsyncClient(base_url=self.base_url, timeout=timeout, headers={"User-Agent": USER_AGENT})
80
+ self._owns_client = http_client is None
81
+
82
+ async def aclose(self) -> None:
83
+ if self._owns_client:
84
+ await self._client.aclose()
85
+
86
+ @staticmethod
87
+ def _headers(api_key: str, extra: dict[str, str] | None = None) -> dict[str, str]:
88
+ headers = {"Authorization": f"Bearer {api_key}", CHANNEL_HEADER: CHANNEL_MCP, "Accept": "application/json"}
89
+ if extra:
90
+ headers.update(extra)
91
+ return headers
92
+
93
+ async def _request(self, method: str, path: str, api_key: str, *, json_body: Any = None, headers: dict[str, str] | None = None) -> httpx.Response:
94
+ try:
95
+ response = await self._client.request(method, path, json=json_body, headers=self._headers(api_key, headers))
96
+ except httpx.TimeoutException as exc:
97
+ raise V1Error(0, "network_timeout", f"API 서버가 제한 시간 안에 응답하지 않았습니다 ({type(exc).__name__}).") from None
98
+ except httpx.HTTPError as exc:
99
+ raise V1Error(0, "network_error", f"API 서버에 닿지 못했습니다 ({type(exc).__name__}).") from None
100
+ if response.status_code >= 400:
101
+ raise _error_from_response(response)
102
+ return response
103
+
104
+ async def list_tools(self, api_key: str) -> list[dict[str, Any]]:
105
+ body = (await self._request("GET", "/v1/tools", api_key)).json()
106
+ tools = body.get("tools") if isinstance(body, dict) else None
107
+ return list(tools) if isinstance(tools, list) else []
108
+
109
+ async def get_tool(self, api_key: str, tool_id: str) -> dict[str, Any]:
110
+ if not TOOL_ID_PATTERN.match(tool_id):
111
+ raise V1Error(422, "validation_error", "도구 ID 형식이 올바르지 않습니다.")
112
+ return (await self._request("GET", f"/v1/tools/{tool_id}", api_key)).json()
113
+
114
+ async def run_tool(self, api_key: str, tool_id: str, tool_input: dict[str, Any], *, idempotency_key: str) -> RunResult:
115
+ if not TOOL_ID_PATTERN.match(tool_id):
116
+ raise V1Error(422, "validation_error", "도구 ID 형식이 올바르지 않습니다.")
117
+ response = await self._request("POST", f"/v1/tools/{tool_id}/run", api_key, json_body={"input": tool_input}, headers={IDEMPOTENCY_HEADER: idempotency_key})
118
+ body = response.json()
119
+ replayed = response.headers.get(REPLAY_HEADER, "").lower() == "true"
120
+ return RunResult(body=body, replayed=replayed, request_id=str(body.get("request_id") or response.headers.get(REQUEST_ID_HEADER) or ""))
121
+
122
+ async def limits(self, api_key: str) -> dict[str, Any]:
123
+ return (await self._request("GET", "/v1/account/limits", api_key)).json()
124
+
125
+ async def download_file(self, api_key: str, file_id: str) -> DownloadedFile:
126
+ if not FILE_ID_PATTERN.match(file_id):
127
+ raise V1Error(422, "validation_error", "파일 ID 형식이 올바르지 않습니다(ULID 26자).")
128
+ response = await self._request("GET", f"/v1/files/{file_id}", api_key, headers={"Accept": "*/*"})
129
+ content_type = response.headers.get("Content-Type", "application/octet-stream").split(";")[0].strip() or "application/octet-stream"
130
+ return DownloadedFile(content=response.content, content_type=content_type, filename=_filename_from_disposition(response.headers.get("Content-Disposition")))
131
+
132
+
133
+ def _error_from_response(response: httpx.Response) -> V1Error:
134
+ request_id = response.headers.get(REQUEST_ID_HEADER)
135
+ try:
136
+ payload = response.json()
137
+ except ValueError:
138
+ payload = None
139
+ error = payload.get("error") if isinstance(payload, dict) else None
140
+ if isinstance(error, dict) and error.get("code"):
141
+ return V1Error(
142
+ response.status_code, str(error.get("code")), str(error.get("message") or ""), request_id=str(error.get("request_id") or request_id or "") or None,
143
+ details=error.get("details"), retry_after_seconds=error.get("retry_after_seconds"),
144
+ )
145
+ # /v1 밖의 오류(스위치가 꺼져 있을 때의 404 등) — 서버 본문은 그대로 믿지 않고 상태코드로만 설명한다
146
+ if response.status_code == 404:
147
+ return V1Error(404, "not_found", "API 경로가 없습니다 — 서버의 API 플랫폼이 꺼져 있거나 주소가 틀렸습니다.", request_id=request_id)
148
+ if response.status_code in (401, 403):
149
+ return V1Error(response.status_code, "unauthorized", "API 키가 거절됐습니다.", request_id=request_id)
150
+ return V1Error(response.status_code, f"http_{response.status_code}", "API 서버가 요청을 처리하지 못했습니다.", request_id=request_id)
151
+
152
+
153
+ def _filename_from_disposition(value: str | None) -> str:
154
+ if not value:
155
+ return "result"
156
+ for part in value.split(";"):
157
+ part = part.strip()
158
+ if part.lower().startswith("filename*="):
159
+ encoded = part.split("=", 1)[1]
160
+ if "''" in encoded:
161
+ return unquote(encoded.split("''", 1)[1]) or "result"
162
+ for part in value.split(";"):
163
+ part = part.strip()
164
+ if part.lower().startswith("filename="):
165
+ return part.split("=", 1)[1].strip('"') or "result"
166
+ return "result"
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: everyonetools-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for the EveryoneTools developer API (/v1): discover and run EveryoneTools tools from MCP clients with your API key.
5
+ Author: EveryoneTools
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://everyonetools.com/developers/mcp
8
+ Project-URL: Documentation, https://everyonetools.com/developers/docs
9
+ Keywords: mcp,model-context-protocol,everyonetools,api,ai-agent
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: mcp<3,>=2.3.0
22
+ Requires-Dist: httpx<1,>=0.28
23
+ Dynamic: license-file
24
+
25
+ # everyonetools-mcp
26
+
27
+ MCP server for the [EveryoneTools developer API](https://everyonetools.com/developers). It lets MCP clients
28
+ (Claude Code, Claude Desktop, Cursor and other MCP-compatible tools) discover and run EveryoneTools tools with
29
+ your API key. Validation, credits and idempotency all happen in the API (`/v1`); this package is a thin wrapper
30
+ and contains no calculation logic.
31
+
32
+ 에브리원툴즈 개발자 API의 MCP 서버입니다. MCP 클라이언트(Claude Code, Claude Desktop, Cursor 등)가 내 API 키로
33
+ 에브리원툴즈 도구를 찾아 실행할 수 있게 합니다. 검증·크레딧·중복 차감 방지는 모두 API(`/v1`)가 처리합니다.
34
+
35
+ ## Requirements
36
+
37
+ - Python 3.11 or later
38
+ - An EveryoneTools API key — sign in at <https://everyonetools.com/developers/dashboard> and create a key
39
+ (the free plan includes 500 credits a month)
40
+
41
+ ## Run
42
+
43
+ ```bash
44
+ uvx everyonetools-mcp # with uv
45
+ pipx run everyonetools-mcp # or with pipx
46
+ ```
47
+
48
+ The server speaks MCP over stdio — your MCP client starts it. Pass the API key **only as an environment
49
+ variable**, never as a command argument, and never paste it into a shared project file or a chat.
50
+
51
+ ```bash
52
+ export EVERYONETOOLS_API_KEY="evt_live_..." # macOS / Linux
53
+ $env:EVERYONETOOLS_API_KEY = "evt_live_..." # Windows PowerShell
54
+ ```
55
+
56
+ `everyonetools-mcp --version` prints the installed version.
57
+
58
+ ## Connect a client
59
+
60
+ Claude Code — project file `.mcp.json` (the key stays in your environment, not in the file):
61
+
62
+ ```json
63
+ {
64
+ "mcpServers": {
65
+ "everyonetools": {
66
+ "command": "uvx",
67
+ "args": ["everyonetools-mcp"],
68
+ "env": { "EVERYONETOOLS_API_KEY": "${EVERYONETOOLS_API_KEY}" }
69
+ }
70
+ }
71
+ }
72
+ ```
73
+
74
+ Other clients use the same command (`uvx everyonetools-mcp`) and the same environment variable. If a client can
75
+ only take the key in its own settings, keep that settings file private and out of version control.
76
+
77
+ ## Tools
78
+
79
+ - The tools the API publishes for MCP — currently `calc_loan`, `calc_vat` and `text_count` (1 credit per
80
+ successful call). Names are the API tool IDs with `.` replaced by `_`.
81
+ - `get_remaining_credits` — plan, balance and limits (not charged).
82
+ - `download_result_file` — download a file produced by a document tool, within its retention (not charged).
83
+ - Repeating the same tool with the same input within 24 hours is charged once
84
+ (`EVERYONETOOLS_MCP_AUTO_IDEMPOTENCY`, default `true`).
85
+
86
+ ## Environment variables
87
+
88
+ | Name | Default | Meaning |
89
+ |---|---|---|
90
+ | `EVERYONETOOLS_API_KEY` | (required) | Your API key |
91
+ | `EVERYONETOOLS_API_BASE` | `https://api.everyonetools.com` | API host |
92
+ | `EVERYONETOOLS_MCP_AUTO_IDEMPOTENCY` | `true` | Fold repeat calls with the same input into one charge |
93
+ | `EVERYONETOOLS_MCP_LANGUAGE` | `ko` | Language shown first in tool names and descriptions (`ko` or `en`) |
94
+
95
+ ## Links
96
+
97
+ - Developer portal: <https://everyonetools.com/developers>
98
+ - API documentation: <https://everyonetools.com/developers/docs>
99
+ - MCP guide: <https://everyonetools.com/developers/mcp>
100
+
101
+ License: MIT
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ PYPI_README.md
4
+ pyproject.toml
5
+ everyonetools_mcp/__init__.py
6
+ everyonetools_mcp/__main__.py
7
+ everyonetools_mcp/http_auth.py
8
+ everyonetools_mcp/server.py
9
+ everyonetools_mcp/v1_client.py
10
+ everyonetools_mcp.egg-info/PKG-INFO
11
+ everyonetools_mcp.egg-info/SOURCES.txt
12
+ everyonetools_mcp.egg-info/dependency_links.txt
13
+ everyonetools_mcp.egg-info/entry_points.txt
14
+ everyonetools_mcp.egg-info/requires.txt
15
+ everyonetools_mcp.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ everyonetools-mcp = everyonetools_mcp.__main__:main
@@ -0,0 +1,2 @@
1
+ mcp<3,>=2.3.0
2
+ httpx<1,>=0.28
@@ -0,0 +1 @@
1
+ everyonetools_mcp
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "everyonetools-mcp"
7
+ version = "0.1.0"
8
+ description = "MCP server for the EveryoneTools developer API (/v1): discover and run EveryoneTools tools from MCP clients with your API key."
9
+ readme = "PYPI_README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "EveryoneTools" }]
14
+ keywords = ["mcp", "model-context-protocol", "everyonetools", "api", "ai-agent"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Topic :: Software Development :: Libraries",
24
+ ]
25
+ dependencies = ["mcp>=2.3.0,<3", "httpx>=0.28,<1"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://everyonetools.com/developers/mcp"
29
+ Documentation = "https://everyonetools.com/developers/docs"
30
+
31
+ [project.scripts]
32
+ everyonetools-mcp = "everyonetools_mcp.__main__:main"
33
+
34
+ [tool.setuptools.packages.find]
35
+ include = ["everyonetools_mcp*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+