# MCP 서버

> Claude Code나 Cursor 같은 AI 클라이언트가 원격 MCP를 통해 API 키로 Kerox 작업의 비용을 추정하고, 작업을 생성하고 조회할 수 있도록 합니다.

이 페이지의 안내에 따라 설정을 마치면 MCP 클라이언트에서 Kerox의 도구를 호출하여 모델 목록 조회, 비용 추정, 작업 생성 및 조회를 할 수 있습니다. `KEROX_API_KEY`의 API 키와 streamable HTTP 기반 원격 서버를 지원하는 MCP 클라이언트가 필요합니다. MCP로 생성한 작업도 다른 작업과 동일하게 과금됩니다.

<a id="endpoint"></a>

## 엔드포인트 및 인증
- **URL**: `https://api.kerox.ai/mcp`
- **헤더**: `Authorization: Bearer <your-api-key>`

MCP로 생성한 작업에는 동일한 요금과 동일한 보류, 정산 및 환불 규칙이 적용됩니다. 이러한 작업은 [Console → Tasks](https://kerox.ai/ko/console/tasks)에 표시되며, `GET /v1/tasks`에서도 `source: "mcp"` 조건으로 확인할 수 있습니다. 키 한도는 MCP에도 적용됩니다([키 한도](https://kerox.ai/ko/docs/authentication.md#limits)).

<a id="setup"></a>

## 클라이언트에 추가
**Claude Code**: 명령어 하나로 모든 프로젝트에 서버를 추가합니다. 명령을 실행하면 셸이 키를 채워 넣습니다.


```bash
# Claude Code: add the server once, for every project.
claude mcp add --transport http --scope user kerox https://api.kerox.ai/mcp \
  --header "Authorization: Bearer $KEROX_API_KEY"
```


**설정 파일**(프로젝트의 Claude Code `.mcp.json` 또는 같은 `mcpServers` 형식을 읽는 클라이언트): `${KEROX_API_KEY}` 값은 클라이언트가 시작될 때 환경 변수에서 채워지므로 키가 파일에 기록되지 않습니다. 클라이언트가 이 파일의 환경 변수 참조를 실제 값으로 치환하지 않는 경우에는 키를 직접 붙여 넣고, 파일을 버전 관리에서 제외하십시오.


```json
{
  "mcpServers": {
    "kerox": {
      "type": "http",
      "url": "https://api.kerox.ai/mcp",
      "headers": {
        "Authorization": "Bearer ${KEROX_API_KEY}"
      }
    }
  }
}
```


<a id="check"></a>

## 연결 확인
클라이언트에 `get_balance` 호출을 요청하십시오. 잔액과 한도가 응답으로 반환되어야 합니다. 클라이언트 문제가 아닌지 확인하려면 클라이언트 없이 같은 호출을 실행해 보십시오:


```bash
curl -sS --fail-with-body -X POST https://api.kerox.ai/mcp \
  -H "Authorization: Bearer $KEROX_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "get_balance", "arguments": {}}}'
```


응답은 계정 객체가 담긴 `data:` 한 줄입니다. 키가 없거나 잘못된 경우 HTTP `401` 응답이 반환됩니다([오류](https://kerox.ai/ko/docs/errors.md#next-steps)).

<a id="first-task"></a>

## 첫 번째 작업
연결되면 서버가 MCP 클라이언트에 워크플로 안내를 보냅니다. `list_models`를 호출하여 `live` 모델의 전체 ID를 복사하고, `get_model_schema`로 입력 항목을 확인합니다. `estimate`를 호출하고 예상 가격을 사용자에게 확인받은 뒤, 같은 모델과 입력으로 `create_task`를 호출합니다. 작업이 `processing` 상태인 동안 3초마다 `get_task`를 폴링합니다. `succeeded` 또는 `failed` 상태가 되면 중지합니다.

모델 ID를 알 수 없으면 도구가 `not_found`를 반환합니다. 비슷한 ID가 있으면 메시지에 게시된 활성 모델 ID가 최대 5개까지 제안됩니다. 제안이 없으면 `list_models`로 전체 ID를 확인하십시오.

Python 3와 `requests`가 있으면 다음 스크립트가 통합 스키마와 예상 가격을 읽고, **과금되는 작업 하나를 제출**한 뒤 첫 번째 출력을 저장합니다. 참조 이미지를 사용하려면 실행 전에 `KEROX_REFERENCE_PNG`를 PNG 파일로 설정하십시오. 이 경우 제출 전에 업로드, PUT, 준비 상태 확인도 함께 실행됩니다.


```python
# pip install requests
import json
import os
import time
import uuid
from pathlib import Path

import requests

api = os.environ.get("KEROX_API_ORIGIN", "https://api.kerox.ai")
auth = {"Authorization": f"Bearer {os.environ['KEROX_API_KEY']}"}

def call(name, arguments):
    response = requests.post(
        f"{api}/mcp",
        headers={**auth, "Accept": "application/json, text/event-stream"},
        json={"jsonrpc": "2.0", "id": 1, "method": "tools/call",
              "params": {"name": name, "arguments": arguments}},
        timeout=60,
    )
    response.raise_for_status()
    message = next(json.loads(line[5:]) for line in response.text.splitlines()
                   if line.startswith("data:"))
    if "error" in message:
        raise RuntimeError(message["error"])
    result = message["result"]
    value = json.loads(result["content"][0]["text"])
    if result.get("isError"):
        raise RuntimeError(value)
    return value

model = "bytedance/seedream-5.5"
schema = call("get_model_schema", {"model": model})
print(schema["unified"]["input_schema"]["properties"].keys())
inputs = {"prompt": "A watercolor of a coastal lighthouse"}
if os.environ.get("KEROX_REFERENCE_PNG"):
    path = Path(os.environ["KEROX_REFERENCE_PNG"])
    file = call("upload_file", {"filename": path.name, "size": path.stat().st_size,
                                "content_type": "image/png"})
    with path.open("rb") as data:
        requests.put(file["upload_url"], headers=file["upload_headers"],
                     data=data, timeout=300).raise_for_status()
    for _ in range(30):
        check = requests.get(f"{api}/v1/files/{file['id']}", headers=auth, timeout=30)
        check.raise_for_status()
        file = check.json()
        if file["status"] == "ready":
            break
        time.sleep(1)
    else:
        raise SystemExit("Upload did not become ready")
    inputs["images"] = [file["url"]]

args = {"model": model, "input": inputs}
estimate = call("estimate", args)
print("Estimated hold (USD):", estimate["amount"])
task = call("create_task", {**args, "idempotency_key": str(uuid.uuid4())})
task_id = task["id"]
print("TASK_ID =", task_id, flush=True)
deadline = time.monotonic() + 600
while task["status"] == "processing":
    if time.monotonic() >= deadline:
        raise SystemExit(f"Resume get_task later with id={task_id}")
    time.sleep(3)
    task = call("get_task", {"id": task_id})
if task["status"] != "succeeded":
    raise SystemExit(task["error"])
output = requests.get(task["outputs"][0]["url"], timeout=60)
output.raise_for_status()
Path("result.png").write_bytes(output.content)
print("Saved result.png")
```


`succeeded` 상태에서는 `outputs[0].url`가 다운로드 주소입니다. `failed` 상태에서는 `error.code`를 확인하십시오. 클라이언트가 대기를 중단하면 출력된 ID를 `get_task`에 사용하여 계속 진행하십시오.

<a id="tools"></a>

## 사용 가능한 도구
| 도구 | 설명 |
| --- | --- |
| `list_models` | 공개된 이미지 및 영상 모델과 현재 가격을 조회합니다 |
| `get_model_schema` | 모델의 파라미터를 확인합니다: `unified.input_schema`(기본 형식) 및 ByteDance 모델의 경우 네이티브 `input_schema` |
| `estimate` | 작업을 생성하지 않고 후보 작업의 비용을 추정합니다 |
| `create_task` | 가격을 추정하고 확인한 후 생성 작업을 제출합니다. `status: "processing"`을(를) 즉시 반환합니다. `id`을(를) 보관하고 재시도할 때는 동일한 `idempotency_key`을(를) 재사용하십시오 |
| `get_task` | 작업 상태, 출력, 비용 또는 오류 세부 정보를 확인합니다. `status`이(가) `succeeded` 또는 `failed`이(가) 될 때까지 호출하십시오 |
| `list_tasks` | 계정의 최근 작업 목록을 조회합니다 |
| `upload_file` | 참조 파일 업로드를 준비합니다. 바이트를 `PUT` 방식으로 전송할 대상인 `upload_url` 및 `upload_headers`, 그리고 입력값으로 사용할 `url` 값을 반환합니다 |
| `get_balance` | 잔액, 보류 금액 및 한도를 조회합니다 |
