# 에이전트에 기기 연결하기

두 가지 방법이 있습니다. 에이전트를 만든다면 첫 번째부터 시작하세요. 2분이면 모의 기기로 실행해 보고, 이어서 내 기기로 확인할 수 있습니다.

원본: https://developer.reachthings.com/docs/quickstart · English: https://developer.reachthings.com/docs/quickstart.md

MCP server: `https://connect.reachthings.com/mcp`

**경로 고르기**

1. [내가 만드는 에이전트에 연동하기](#build): 내 앱에서 “공유한 기기 상태를 알려줘”라고 물으면 에이전트가 실제 상태를 조회해 답하도록 만듭니다.
2. [이미 쓰는 AI 도구에 연결하기](#ai-tools): Claude, ChatGPT, Claude Code, Codex 등에서 Reachthings를 연결하고 공유한 기기를 조회합니다.

## 내가 만드는 에이전트에 연동하기

Claude Code 나 Codex 같은 코딩 에이전트로 작업한다면 이 페이지 주소와 아래 한 문장만 주세요. 필요한 내용은 이 페이지에서 찾고, 모의 기기로 먼저 검증한 뒤, 로그인이나 기기 공유가 필요할 때 알려 줍니다.

**코딩 에이전트에 복사** (한국어):

> https://developer.reachthings.com/docs/quickstart 를 읽고 이 프로젝트의 에이전트에 Reachthings를 연동해 줘. 기존 구조와 SDK를 확인하고, 사용자가 공유한 기기 상태를 물으면 실제 조회 결과로 답하게 해 줘. 먼저 모의 기기로 검증하고, 내 로그인이나 기기 공유가 필요할 때 해당 화면과 다음 행동을 알려줘.

Copy for your coding agent (English):

> Read https://developer.reachthings.com/docs/quickstart and integrate Reachthings into this project's agent. Check the existing structure and SDK first, and make the agent answer questions about the user's shared devices with real lookup results. Verify with mock devices first, and when you need me to sign in or share devices, tell me which screen to open and what to do next.

직접 진행한다면 아래 단계를 따르세요. 코딩 에이전트도 같은 단계를 따릅니다. 필요한 것은 Node 20 이상과 npm 입니다. 3단계 전까지는 계정이 필요 없습니다.

## 1. 모의 기기로 스타터 실행

스타터는 작은 TypeScript 에이전트입니다. 모의 기기로 실행하면 모두 내 컴퓨터 안에서 돕니다. 모의 서버는 Reachthings 와 도구 이름·응답 모양이 같고, `ANTHROPIC_API_KEY` 가 없으면 정해진 규칙으로 움직이는 대역이 모델 자리를 맡아 전체 흐름이 그대로 돕니다.

```bash
mkdir reachthings-agent && cd reachthings-agent
for f in package.json tsconfig.json agent.ts control.ts model.ts reachthings.ts mock-reachthings.ts; do
  curl -fsSLO "https://developer.reachthings.com/docs/quickstart/starter/$f"
done
npm install
npm run mock
```

예상 출력(시각은 다릅니다):

```text
Devices: mock (in-process)
Model:   scripted stand-in (set ANTHROPIC_API_KEY to use Claude)

You: What's the status of my shared devices?
  → list_devices {}
  → get_device_state {"device_id":"dev_mock_ac"}
  → get_device_state {"device_id":"dev_mock_plug"}
  → get_device_state {"device_id":"dev_mock_lock"}

Agent: Here's what your shared devices report:
- Living room AC (online): power: off, target_temperature: 24, current_temperature: 27.5.
- Desk lamp plug (offline): outlet_power: on (stale, observed 2026-11-15T10:58:22.621Z). Couldn't refresh it (DEVICE_OFFLINE), so these are the last known values.
- Front door (online): lock: locked (stale, observed 2026-11-15T14:06:22.621Z), battery: never reported.
```

기기마다 이름과 보고된 값으로 답합니다. 오래된 값은 관측 시각을 함께 말하고, 기기가 한 번도 보고하지 않은 값은 그렇다고 말하며, 오프라인 기기는 마지막 값과 이유를 돌려줍니다.

공유된 기기가 없을 때 에이전트가 하는 말은 `npm run mock -- --empty` 로 볼 수 있습니다:

```text
Agent: I can't see any shared devices yet. In the Reachthings console, check: (1) Devices — the device account is connected, (2) the device is active for agents, (3) Agents → this agent — the device is shared. Then ask me again.
```

Claude 를 모델로 쓰려면 `ANTHROPIC_API_KEY` 를 설정하고(필요하면 `ANTHROPIC_MODEL`, 기본 `claude-sonnet-5-5`) `npm run mock` 을 다시 실행하세요. 도구 호출은 같고 답은 모델이 씁니다.

### 스타터 파일 전체

파일마다 `https://developer.reachthings.com/docs/quickstart/starter/<파일>` 에서도 받을 수 있습니다.

#### package.json

```json
{
  "name": "reachthings-agent-starter",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=20" },
  "scripts": {
    "mock": "tsx agent.ts --mock",
    "start": "tsx agent.ts",
    "control": "tsx control.ts",
    "typecheck": "tsc --noEmit"
  },
  "dependencies": {
    "@anthropic-ai/sdk": "1.3.0",
    "@modelcontextprotocol/sdk": "1.32.1",
    "zod": "4.6.7"
  },
  "devDependencies": {
    "@types/node": "22.20.5",
    "tsx": "4.23.15",
    "typescript": "5.9.3"
  }
}
```

#### tsconfig.json

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "skipLibCheck": true,
    "noEmit": true
  },
  "include": ["*.ts"]
}
```

#### agent.ts

```ts
// Ask about your shared devices.
//   npm run mock                      mock devices (no account)
//   npm run mock -- --empty           mock with no shared devices
//   npm start                         your real devices (signs in on first run)
//   npm start -- "Is the AC on?"      ask something else
import { connectReachthings, MCP_URL } from "./reachthings.js";
import { ask, pickModel } from "./model.js";

const args = process.argv.slice(2);
const mock = args.includes("--mock");
if (args.includes("--empty")) process.env.MOCK_DEVICES = "empty";
const question = args.filter((a) => !a.startsWith("--")).join(" ") || "What's the status of my shared devices?";

const model = pickModel();
console.log(`Devices: ${mock ? "mock (in-process)" : MCP_URL}`);
console.log(`Model:   ${model.name}`);
console.log(`\nYou: ${question}`);
const client = await connectReachthings(mock ? "mock" : "live");
try {
  const answer = await ask(client, question, { model });
  console.log(`\nAgent: ${answer}`);
} finally {
  await client.close();
}
```

#### control.ts

```ts
// Run one device action and follow it to a final result.
//   npm run control                                  mock: turn the mock AC on
//   npm run control -- --approval                    mock: an action that needs the owner's approval
//   npm run control -- --live <device_id> <action> '<parameters JSON>'
// Accepted is not done: the result comes from get_command_status with the same command_id.
import { randomUUID } from "node:crypto";
import { connectReachthings } from "./reachthings.js";

const args = process.argv.slice(2);
const live = args.includes("--live");
const pos = args.filter((a) => !a.startsWith("--"));
const [deviceId, action, params] = live
  ? [pos[0], pos[1], pos[2] ?? "{}"]
  : args.includes("--approval") ? ["dev_mock_lock", "door.unlock", "{}"] : ["dev_mock_ac", "appliance.power.set", '{"power":"on"}'];
if (!deviceId || !action) {
  console.error("usage: npm run control -- --live <device_id> <action> '<parameters JSON>'");
  process.exit(2);
}

type Command = { command_id: string | null; status: string; reason_code: string | null; verification?: { level: string }; approval?: { url: string } | null; next_action?: { type: string; message: string }; next_poll_after_ms?: number | null; error?: { code: string; message: string } };
const TERMINAL = new Set(["succeeded", "failed", "rejected", "cancelled", "expired", "outcome_unknown"]);

const client = await connectReachthings(live ? "live" : "mock");
try {
  // 1. Only run an action this agent is allowed to run on this device
  const device = (await client.callTool({ name: "get_device", arguments: { device_id: deviceId } })).structuredContent as { alias: string | null; capabilities?: Array<{ id: string; approval: string }>; error?: { code: string } };
  const cap = device.capabilities?.find((c) => c.id === action);
  if (!cap) {
    console.log(`${action} isn't allowed for this agent on ${device.alias ?? deviceId}${device.error ? ` (${device.error.code})` : ""}. Allow it under Agents in the console.`);
    process.exit(1);
  }
  console.log(`${device.alias}: ${action} ${params}${cap.approval === "per_command" ? " (needs the owner's approval)" : ""}`);

  // 2. Send it once. Reuse the same request_key if you have to resend after a network error
  let cmd = (await client.callTool({ name: "execute_device_action", arguments: { device_id: deviceId, action, parameters: JSON.parse(params), request_key: randomUUID() } })).structuredContent as Command;
  if (!cmd.command_id) {
    console.log(`Not sent: ${cmd.error?.code} ${cmd.error?.message}`);
    process.exit(1);
  }
  console.log(`command ${cmd.command_id}: ${cmd.status}`);

  // 3. Follow next_action with the same command_id until the status is final
  let shownApproval = false;
  while (!TERMINAL.has(cmd.status)) {
    if (cmd.next_action?.type === "open_approval_url" && cmd.approval && !shownApproval) {
      console.log(`Waiting for approval. Ask the owner to open: ${cmd.approval.url}`);
      shownApproval = true;
    }
    await new Promise((r) => setTimeout(r, cmd.next_poll_after_ms ?? 1000));
    cmd = (await client.callTool({ name: "get_command_status", arguments: { command_id: cmd.command_id, wait_ms: 5000 } })).structuredContent as Command;
    console.log(`command ${cmd.command_id}: ${cmd.status}`);
  }

  // 4. Report what actually happened. outcome_unknown may or may not have run: never resend it automatically
  if (cmd.status === "succeeded") console.log(`Done: ${action} succeeded (verified: ${cmd.verification?.level}).`);
  else if (cmd.status === "outcome_unknown") console.log("Sent, but the result couldn't be confirmed. Check the device before trying again.");
  else console.log(`Not done: ${cmd.status}${cmd.reason_code ? ` (${cmd.reason_code})` : ""}. ${cmd.next_action?.message ?? ""}`);
} finally {
  await client.close();
}
```

#### model.ts

```ts
// The agent loop: give the model the Reachthings tools, run the tools it picks over MCP,
// send the results back, repeat until it answers.
//   ANTHROPIC_API_KEY set → Claude (ANTHROPIC_MODEL, default claude-sonnet-5-5)
//   not set               → a scripted stand-in with the same request/response shape, so the
//                           loop runs end to end without a key. It is not a language model.
import Anthropic from "@anthropic-ai/sdk";
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";

type Message = Anthropic.Messages.MessageParam;
type Tool = Anthropic.Messages.Tool;
type Block = Anthropic.Messages.ContentBlock;
interface Turn { content: Block[]; stop_reason: string | null }
interface Model { name: string; create(p: { system: string; tools: Tool[]; messages: Message[] }): Promise<Turn> }

/** Read-only tools are enough to answer "what's the status of my devices?" */
const READ_TOOLS = ["list_devices", "get_device", "get_device_state"];

export const SYSTEM = `You answer questions about the user's devices through Reachthings tools.
To report device status: call list_devices, then get_device_state for each device_id it returns.
Answer with each device's name (alias) and the observed values. Say when a value is stale (fresh: false)
and give its observed_at, say when a value is null (never reported), and mention connector_error if present.
Never guess a value that the tools did not return.
If list_devices returns no devices, say so and tell the user to check in the Reachthings console:
(1) Devices: the device account is connected (not "Reconnect"), (2) the device is active for agents,
(3) Agents → this agent: the device is shared. Then ask again.`;

export function pickModel(): Model {
  if (process.env.ANTHROPIC_API_KEY) {
    const anthropic = new Anthropic();
    const model = process.env.ANTHROPIC_MODEL ?? "claude-sonnet-5-5";
    return {
      name: model,
      create: async ({ system, tools, messages }) => anthropic.messages.create({ model, max_tokens: 1024, system, tools, messages }),
    };
  }
  return scriptedModel;
}

export async function ask(client: Client, question: string, opts: { model?: Model; log?: (line: string) => void } = {}): Promise<string> {
  const model = opts.model ?? pickModel();
  const log = opts.log ?? ((l: string) => console.log(l));
  const { tools: mcpTools } = await client.listTools();
  const tools: Tool[] = mcpTools
    .filter((t) => READ_TOOLS.includes(t.name))
    .map((t) => ({ name: t.name, description: t.description ?? "", input_schema: t.inputSchema as Tool["input_schema"] }));
  const messages: Message[] = [{ role: "user", content: question }];
  for (let round = 0; round < 10; round++) {
    const turn = await model.create({ system: SYSTEM, tools, messages });
    messages.push({ role: "assistant", content: turn.content });
    const calls = turn.content.filter((b): b is Anthropic.Messages.ToolUseBlock => b.type === "tool_use");
    if (turn.stop_reason !== "tool_use" || calls.length === 0) {
      return turn.content.filter((b): b is Anthropic.Messages.TextBlock => b.type === "text").map((b) => b.text).join("\n");
    }
    const results: Anthropic.Messages.ToolResultBlockParam[] = [];
    for (const call of calls) {
      log(`  → ${call.name} ${JSON.stringify(call.input)}`);
      const r = await client.callTool({ name: call.name, arguments: call.input as Record<string, unknown> });
      const body = r.structuredContent ?? r.content;
      results.push({ type: "tool_result", tool_use_id: call.id, content: JSON.stringify(body), is_error: r.isError === true });
    }
    messages.push({ role: "user", content: results });
  }
  throw new Error("The model kept calling tools without answering");
}

// ---------- scripted stand-in (no API key) ----------

let seq = 0;
const toolUse = (name: string, input: object): Block => ({ type: "tool_use", id: `toolu_mock_${++seq}`, name, input, caller: { type: "direct" } } as unknown as Block);
const text = (t: string): Block => ({ type: "text", text: t, citations: null } as unknown as Block);

/** Follows SYSTEM by rule: list_devices → get_device_state for each → a summary of what came back */
const scriptedModel: Model = {
  name: "scripted stand-in (set ANTHROPIC_API_KEY to use Claude)",
  async create({ messages }) {
    const results = new Map<string, unknown>();
    const uses = new Map<string, { name: string; input: Record<string, unknown> }>();
    for (const m of messages) {
      if (!Array.isArray(m.content)) continue;
      for (const b of m.content) {
        if (b.type === "tool_use") uses.set(b.id, { name: b.name, input: b.input as Record<string, unknown> });
        if (b.type === "tool_result") results.set(b.tool_use_id, JSON.parse(String(b.content)));
      }
    }
    const resultOf = (name: string) => [...uses].filter(([, u]) => u.name === name).map(([id, u]) => ({ input: u.input, out: results.get(id) as Record<string, any> | undefined }));
    const listed = resultOf("list_devices")[0]?.out;
    if (!listed) return { content: [toolUse("list_devices", {})], stop_reason: "tool_use" };
    const devices: Array<{ device_id: string; alias: string | null; kind: string; connection_status: string }> = listed.devices ?? [];
    if (devices.length === 0) {
      return {
        content: [text("I can't see any shared devices yet. In the Reachthings console, check: (1) Devices — the device account is connected, (2) the device is active for agents, (3) Agents → this agent — the device is shared. Then ask me again.")],
        stop_reason: "end_turn",
      };
    }
    const states = resultOf("get_device_state");
    const missing = devices.filter((d) => !states.some((s) => s.input.device_id === d.device_id));
    if (missing.length) return { content: missing.map((d) => toolUse("get_device_state", { device_id: d.device_id })), stop_reason: "tool_use" };
    const lines = devices.map((d) => {
      const s = states.find((x) => x.input.device_id === d.device_id)?.out ?? {};
      const values = (s.attributes ?? []).map((a: { attribute: string; value: unknown; fresh: boolean; observed_at: string | null }) =>
        a.value === null ? `${a.attribute}: never reported` : `${a.attribute}: ${String(a.value)}${a.fresh ? "" : ` (stale, observed ${a.observed_at})`}`,
      );
      const err = s.connector_error ? ` Couldn't refresh it (${s.connector_error.code}), so these are the last known values.` : "";
      return `- ${d.alias ?? d.kind} (${d.connection_status}): ${values.join(", ") || "no readable state"}.${err}`;
    });
    return { content: [text(`Here's what your shared devices report:\n${lines.join("\n")}`)], stop_reason: "end_turn" };
  },
};
```

#### reachthings.ts

```ts
// Connects an MCP client to Reachthings.
//   mock: an in-process mock server (no account, no network)
//   live: https://connect.reachthings.com/mcp with OAuth (Authorization Code + PKCE)
//
// Live sign-in uses a client ID metadata document (CIMD): the client_id is a URL.
// The default is Reachthings' shared starter client, made for local development.
// Your own app publishes its own document and sets RT_CLIENT_ID to its URL.
import { createServer } from "node:http";
import { readFile, writeFile } from "node:fs/promises";
import { spawn } from "node:child_process";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { UnauthorizedError, type OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js";
import type { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js";
import { createMockReachthings } from "./mock-reachthings.js";

export const MCP_URL = process.env.RT_MCP_URL ?? "https://connect.reachthings.com/mcp";
export const CLIENT_ID = process.env.RT_CLIENT_ID ?? "https://developer.reachthings.com/docs/oauth/starter-client.json";
const CALLBACK_PORT = Number(process.env.RT_CALLBACK_PORT ?? 8976);
const REDIRECT_URL = `http://127.0.0.1:${CALLBACK_PORT}/callback`;
const TOKEN_FILE = process.env.RT_TOKEN_FILE ?? ".reachthings-tokens.json"; // keep it out of git

/**
 * Saved tokens are only reused when the file says which client_id they were issued to and it matches the current one.
 * A file without client_id (written by an older starter) or for another client_id (for example the shared starter ID after you set RT_CLIENT_ID to your own) is ignored, so you sign in again.
 */
export async function readSavedTokens(file: string, clientId: string): Promise<OAuthTokens | undefined> {
  try {
    const saved = JSON.parse(await readFile(file, "utf8")) as OAuthTokens & { client_id?: unknown };
    if (saved.client_id !== clientId) return undefined;
    const { client_id: _ignored, ...tokens } = saved;
    return tokens as OAuthTokens;
  } catch {
    return undefined;
  }
}
export async function writeSavedTokens(file: string, clientId: string, tokens: OAuthTokens): Promise<void> {
  await writeFile(file, JSON.stringify({ ...tokens, client_id: clientId }), { mode: 0o600 });
}

export async function connectReachthings(mode: "mock" | "live"): Promise<Client> {
  const client = new Client({ name: "reachthings-agent-starter", version: "1.0.0" });
  if (mode === "mock") {
    const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
    await createMockReachthings().connect(serverSide);
    await client.connect(clientSide);
    return client;
  }
  const provider = new LoopbackOAuthProvider();
  try {
    await client.connect(new StreamableHTTPClientTransport(new URL(MCP_URL), { authProvider: provider }));
    return client;
  } catch (e) {
    if (!(e instanceof UnauthorizedError)) throw e;
  }
  // First run (or the refresh token expired): the browser sign-in was opened, wait for the callback
  const code = await provider.waitForCode();
  const transport = new StreamableHTTPClientTransport(new URL(MCP_URL), { authProvider: provider });
  await transport.finishAuth(code);
  const signedIn = new Client({ name: "reachthings-agent-starter", version: "1.0.0" });
  await signedIn.connect(new StreamableHTTPClientTransport(new URL(MCP_URL), { authProvider: provider }));
  return signedIn;
}

/** OAuth for a command-line app: tokens in a local file, consent in the browser, callback on 127.0.0.1 */
class LoopbackOAuthProvider implements OAuthClientProvider {
  readonly clientMetadataUrl = CLIENT_ID;
  private verifier = "";
  private pending: Promise<string> | null = null;

  get redirectUrl(): string {
    return REDIRECT_URL;
  }
  get clientMetadata(): OAuthClientMetadata {
    return { client_name: "Reachthings agent starter", redirect_uris: [REDIRECT_URL], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none" };
  }
  clientInformation(): OAuthClientInformationMixed {
    return { client_id: CLIENT_ID };
  }
  async tokens(): Promise<OAuthTokens | undefined> {
    return readSavedTokens(TOKEN_FILE, CLIENT_ID);
  }
  async saveTokens(tokens: OAuthTokens): Promise<void> {
    await writeSavedTokens(TOKEN_FILE, CLIENT_ID, tokens);
  }
  saveCodeVerifier(v: string): void {
    this.verifier = v;
  }
  codeVerifier(): string {
    return this.verifier;
  }
  async redirectToAuthorization(url: URL): Promise<void> {
    this.pending = listenForCode();
    console.log(`\nSign in to Reachthings in your browser (opening it now):\n${url.href}\n`);
    if (process.env.RT_OPEN_BROWSER !== "0") {
      const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
      spawn(opener, [url.href], { stdio: "ignore", detached: true }).on("error", () => undefined).unref();
    }
  }
  waitForCode(): Promise<string> {
    if (!this.pending) throw new Error("Sign-in was not started");
    return this.pending;
  }
}

/** Receives ?code= on the redirect URL once, then closes */
function listenForCode(): Promise<string> {
  return new Promise((resolve, reject) => {
    const server = createServer((req, res) => {
      const u = new URL(req.url ?? "/", REDIRECT_URL);
      if (u.pathname !== "/callback") return void res.writeHead(404).end();
      const code = u.searchParams.get("code");
      const error = u.searchParams.get("error");
      res.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end(code ? "Signed in. You can close this tab and go back to the terminal." : `Sign-in failed: ${error ?? "no code"}`);
      server.close();
      if (code) resolve(code);
      else reject(new Error(`Sign-in failed: ${error ?? "no code"} ${u.searchParams.get("error_description") ?? ""}`.trim()));
    });
    server.on("error", reject);
    server.listen(CALLBACK_PORT, "127.0.0.1");
  });
}
```

#### mock-reachthings.ts

```ts
// Mock Reachthings MCP server: the same tool names and response shapes as
// https://connect.reachthings.com/mcp, with made-up devices. Runs in-process,
// so you can build and test your agent without an account or real devices.
//
//   MOCK_DEVICES=empty   → list_devices returns no devices (try the empty-list path)
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

type Value = string | number | boolean | null;
interface MockDevice {
  device_id: string;
  alias: string;
  kind: string;
  connection_status: "online" | "offline" | "unknown";
  /** attribute → [value, minutes since the manufacturer observed it] (null = never reported) */
  state: Record<string, [Value, number] | null>;
  actions: Array<{ id: string; input_schema: object; approval: "none" | "per_command"; verifies: string; param: string }>;
}

const MAX_AGE_MS = 60_000;

function devices(): MockDevice[] {
  if (process.env.MOCK_DEVICES === "empty") return [];
  return [
    {
      device_id: "dev_mock_ac", alias: "Living room AC", kind: "air_conditioner", connection_status: "online",
      state: { power: ["off", 0], target_temperature: [24, 0], current_temperature: [27.5, 0] },
      actions: [{ id: "appliance.power.set", input_schema: { type: "object", properties: { power: { type: "string", enum: ["on", "off"] } }, required: ["power"], additionalProperties: false }, approval: "none", verifies: "power", param: "power" }],
    },
    {
      device_id: "dev_mock_plug", alias: "Desk lamp plug", kind: "smart_plug", connection_status: "offline",
      state: { outlet_power: ["on", 190] },
      actions: [],
    },
    {
      device_id: "dev_mock_lock", alias: "Front door", kind: "lock", connection_status: "online",
      state: { lock: ["locked", 2], battery: null },
      actions: [{ id: "door.unlock", input_schema: { type: "object", properties: {}, additionalProperties: false }, approval: "per_command", verifies: "lock", param: "" }],
    },
  ];
}

const json = (body: object) => ({ content: [{ type: "text" as const, text: JSON.stringify(body) }], structuredContent: body as Record<string, unknown> });
const toolError = (code: string, message: string) => ({ ...json({ command_id: null, error: { code, message } }), isError: true });

interface MockCommand { command_id: string; device: MockDevice; action: string; parameters: Record<string, unknown>; polls: number; needsApproval: boolean }

export function createMockReachthings(): McpServer {
  const server = new McpServer({ name: "reachthings-mock", version: "1.0.0" });
  const all = devices();
  const commands = new Map<string, MockCommand>();
  const byKey = new Map<string, string>();
  const find = (id: string) => all.find((d) => d.device_id === id);

  server.registerTool("list_devices", {
    title: "List allowed devices",
    description: "Returns only the devices allowed for this connection and activated by the owner: device ID, alias, kind, and connection status.",
    inputSchema: {},
    annotations: { readOnlyHint: true },
  }, async () => json({ devices: all.map(({ device_id, alias, kind, connection_status }) => ({ device_id, alias, kind, connection_status })) }));

  server.registerTool("get_device", {
    title: "Get device details",
    description: "Device details and the actions this agent may run on it, with their input schema and whether approval is required.",
    inputSchema: { device_id: z.string() },
    annotations: { readOnlyHint: true },
  }, async ({ device_id }) => {
    const d = find(device_id);
    if (!d) return toolError("DEVICE_NOT_ACCESSIBLE", "The requested device was not found or is not accessible from this connection.");
    return json({
      device_id: d.device_id, alias: d.alias, kind: d.kind, model: "MOCK-1", control_path: "manufacturer_cloud", connection_status: d.connection_status,
      capabilities: d.actions.map((a) => ({ id: a.id, version: 1, kind: "set", input_schema: a.input_schema, output_schema: null, approval: a.approval, idempotent: true, preconditions: [], completion_rule: "state_observed", verification: { attribute: a.verifies, parameter: a.param || null, sources: ["manufacturer_state"], freshness_ms: MAX_AGE_MS }, last_execution: null, last_verified_at: null })),
    });
  });

  server.registerTool("get_device_state", {
    title: "Read device state",
    description: "Current observed state of a device. Each value carries when it was observed and whether it is fresh.",
    inputSchema: { device_id: z.string(), attributes: z.array(z.string()).optional(), max_age_ms: z.number().int().optional() },
    annotations: { readOnlyHint: true },
  }, async ({ device_id, attributes, max_age_ms }) => {
    const d = find(device_id);
    if (!d) return toolError("DEVICE_NOT_ACCESSIBLE", "The requested device was not found or is not accessible from this connection.");
    const now = Date.now();
    const maxAge = max_age_ms ?? MAX_AGE_MS;
    const wanted = attributes?.length ? attributes : Object.keys(d.state);
    const result = wanted.map((attribute) => {
      const s = d.state[attribute];
      if (!s) return { attribute, value: null, source: null, observed_at: null, received_at: null, fresh: false };
      const at = new Date(now - s[1] * 60_000).toISOString();
      return { attribute, value: s[0], source: "manufacturer_state", observed_at: at, received_at: at, fresh: s[1] * 60_000 <= maxAge };
    });
    // An offline device can't be refreshed: the last stored values come back with the reason
    const offline = d.connection_status === "offline" ? { connector_error: { code: "DEVICE_OFFLINE", retryable: true } } : {};
    return json({ device_id: d.device_id, attributes: result, checked_at: new Date(now).toISOString(), ...offline });
  });

  const view = (c: MockCommand) => {
    // Mock lifecycle: approval (if needed) → queued → dispatching → succeeded, one step per poll
    const step = c.polls;
    const waiting = c.needsApproval && step < 2;
    const status = waiting ? "waiting_approval" : step < (c.needsApproval ? 3 : 1) ? "queued" : step < (c.needsApproval ? 4 : 2) ? "dispatching" : "succeeded";
    const done = status === "succeeded";
    return {
      command_id: c.command_id, status, reason_code: null, device_id: c.device.device_id, action: c.action, parameters: c.parameters,
      verification: { level: done ? "state_observed" : "none", required_level: "state_observed", provider_status: done ? "completed" : "unknown", target_match: done ? "matched" : "not_checked", source: done ? "manufacturer_state" : null, observed_at: done ? new Date().toISOString() : null, deadline_at: null },
      approval: waiting ? { approval_id: `apr_${c.command_id}`, url: `https://connect.reachthings.com/app/approvals/apr_${c.command_id}`, expires_at: new Date(Date.now() + 10 * 60_000).toISOString() } : null,
      next_action: waiting
        ? { type: "open_approval_url", message: "The device owner must approve this in the Reachthings console. (Mock: approves itself after two checks.)" }
        : done
          ? { type: "show_result", message: "The device reports the requested state." }
          : { type: "poll_command_status", message: "The request has been saved. Check the status of the existing command." },
      next_poll_after_ms: done ? null : 500,
    };
  };

  server.registerTool("execute_device_action", {
    title: "Run a device action",
    description: "Creates a command for an allowed action. Returns at once with a command_id; follow next_action and check get_command_status with the same command_id.",
    inputSchema: { device_id: z.string(), action: z.string(), parameters: z.record(z.string(), z.unknown()).optional(), request_key: z.string().min(8) },
    annotations: { destructiveHint: true },
  }, async ({ device_id, action, parameters, request_key }) => {
    const existing = byKey.get(request_key);
    if (existing) return json(view(commands.get(existing)!));
    const d = find(device_id);
    if (!d) return toolError("DEVICE_NOT_ACCESSIBLE", "The requested device was not found or is not accessible from this connection.");
    const a = d.actions.find((x) => x.id === action);
    if (!a) return toolError("PERMISSION_DENIED", "This connection is not allowed to run the requested capability on this device.");
    const c: MockCommand = { command_id: `cmd_mock_${commands.size + 1}`, device: d, action, parameters: parameters ?? {}, polls: 0, needsApproval: a.approval === "per_command" };
    commands.set(c.command_id, c);
    byKey.set(request_key, c.command_id);
    return json(view(c));
  });

  server.registerTool("get_command_status", {
    title: "Get command status",
    description: "Current status of a command. Pass wait_ms to wait for a change.",
    inputSchema: { command_id: z.string(), wait_ms: z.number().int().optional() },
    annotations: { readOnlyHint: true },
  }, async ({ command_id }) => {
    const c = commands.get(command_id);
    if (!c) return toolError("COMMAND_NOT_ACCESSIBLE", "The requested command was not found or is not accessible from this connection.");
    c.polls++;
    const v = view(c);
    if (v.status === "succeeded" && v.verification.level === "state_observed") {
      const a = c.device.actions.find((x) => x.id === c.action)!;
      if (a.param) c.device.state[a.verifies] = [c.parameters[a.param] as Value, 0];
      if (a.id === "door.unlock") c.device.state.lock = ["unlocked", 0];
    }
    return json(v);
  });

  return server;
}
```

#### quickstart.py

```python
"""Read the state of the devices shared with your agent.

    python -m venv .venv && . .venv/bin/activate
    pip install "mcp==2.3.0"
    python quickstart.py --mock     # mock devices, no account
    python quickstart.py            # your real devices (signs in on first run)

Live sign-in uses a client ID metadata document (CIMD): the client_id is a URL.
The default is Reachthings' shared starter client for local development; set
RT_CLIENT_ID to your own document's URL for your app.
"""

import asyncio
import json
import os
import sys
import webbrowser
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from urllib.parse import parse_qs, urlparse

import httpx2
from mcp import Client
from mcp.client.auth import OAuthClientProvider, TokenStorage
from mcp.client.streamable_http import streamable_http_client
from mcp.server import MCPServer
from mcp.shared.auth import AuthorizationCodeResult, OAuthClientInformationFull, OAuthClientMetadata, OAuthToken

MCP_URL = os.environ.get("RT_MCP_URL", "https://connect.reachthings.com/mcp")
CLIENT_ID = os.environ.get("RT_CLIENT_ID", "https://developer.reachthings.com/docs/oauth/starter-client.json")
CALLBACK_PORT = int(os.environ.get("RT_CALLBACK_PORT", "8976"))
REDIRECT_URL = f"http://127.0.0.1:{CALLBACK_PORT}/callback"
TOKEN_FILE = os.environ.get("RT_TOKEN_FILE", ".reachthings-tokens-py.json")  # keep it out of git


# ---------- live: OAuth with a loopback callback ----------

def read_token_file(path, client_id):
    """Saved tokens are reused only when the file says which client_id they were issued to and it matches.
    A file without client_id (older starter) or for another client_id (the shared starter ID after you set RT_CLIENT_ID) is ignored."""
    try:
        with open(path) as f:
            saved = json.load(f)
    except (FileNotFoundError, ValueError):
        return None
    if not isinstance(saved, dict) or saved.get("client_id") != client_id:
        return None
    saved.pop("client_id", None)
    return saved


def write_token_file(path, client_id, data):
    data = dict(data)
    data["client_id"] = client_id
    with open(path, "w") as f:
        json.dump(data, f)
    os.chmod(path, 0o600)


class FileTokens(TokenStorage):
    async def get_tokens(self):
        saved = read_token_file(TOKEN_FILE, CLIENT_ID)
        return OAuthToken.model_validate(saved) if saved is not None else None

    async def set_tokens(self, tokens):
        write_token_file(TOKEN_FILE, CLIENT_ID, json.loads(tokens.model_dump_json()))

    async def get_client_info(self):
        return None

    async def set_client_info(self, client_info: OAuthClientInformationFull):
        pass


async def open_browser(url: str) -> None:
    print(f"\nSign in to Reachthings in your browser (opening it now):\n{url}\n")
    if os.environ.get("RT_OPEN_BROWSER") != "0":
        webbrowser.open(url)


async def wait_for_code() -> AuthorizationCodeResult:
    result: dict = {}

    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            q = parse_qs(urlparse(self.path).query)
            result.update({k: v[0] for k, v in q.items()})
            self.send_response(200)
            self.send_header("content-type", "text/plain; charset=utf-8")
            self.end_headers()
            self.wfile.write(b"Signed in. You can close this tab and go back to the terminal." if "code" in q else b"Sign-in failed.")

        def log_message(self, *args):
            pass

    server = HTTPServer(("127.0.0.1", CALLBACK_PORT), Handler)
    thread = Thread(target=server.handle_request, daemon=True)
    thread.start()
    while thread.is_alive():
        await asyncio.sleep(0.2)
    server.server_close()
    if "code" not in result:
        raise RuntimeError(f"Sign-in failed: {result.get('error', 'no code')} {result.get('error_description', '')}")
    return AuthorizationCodeResult(code=result["code"], state=result.get("state"), iss=result.get("iss"))


def live_client() -> Client:
    oauth = OAuthClientProvider(
        server_url=MCP_URL,
        client_metadata=OAuthClientMetadata(
            client_name="Reachthings agent starter (Python)",
            redirect_uris=[REDIRECT_URL],
            grant_types=["authorization_code", "refresh_token"],
            response_types=["code"],
            token_endpoint_auth_method="none",
        ),
        storage=FileTokens(),
        redirect_handler=open_browser,
        callback_handler=wait_for_code,
        client_metadata_url=CLIENT_ID,
    )
    http = httpx2.AsyncClient(auth=oauth, timeout=httpx2.Timeout(30, read=300))
    return Client(streamable_http_client(MCP_URL, http_client=http), mode="legacy")


# ---------- mock: same tool names and response shapes, made-up devices ----------

def mock_server() -> MCPServer:
    mcp = MCPServer("reachthings-mock")
    now = datetime.now(timezone.utc)
    devices = [] if os.environ.get("MOCK_DEVICES") == "empty" else [
        {"device_id": "dev_mock_ac", "alias": "Living room AC", "kind": "air_conditioner", "connection_status": "online",
         "state": {"power": ("off", 0), "target_temperature": (24, 0), "current_temperature": (27.5, 0)}},
        {"device_id": "dev_mock_plug", "alias": "Desk lamp plug", "kind": "smart_plug", "connection_status": "offline",
         "state": {"outlet_power": ("on", 190)}},
    ]

    @mcp.tool()
    def list_devices() -> dict:
        """Devices shared with this agent and activated by the owner."""
        return {"devices": [{k: d[k] for k in ("device_id", "alias", "kind", "connection_status")} for d in devices]}

    @mcp.tool()
    def get_device_state(device_id: str) -> dict:
        """Observed state of a device, with observed_at and fresh for each value."""
        d = next((x for x in devices if x["device_id"] == device_id), None)
        if d is None:
            return {"command_id": None, "error": {"code": "DEVICE_NOT_ACCESSIBLE", "message": "The requested device was not found or is not accessible from this connection."}}
        attrs = []
        for name, (value, minutes) in d["state"].items():
            at = (now - timedelta(minutes=minutes)).isoformat()
            attrs.append({"attribute": name, "value": value, "source": "manufacturer_state", "observed_at": at, "received_at": at, "fresh": minutes == 0})
        body = {"device_id": device_id, "attributes": attrs, "checked_at": now.isoformat()}
        if d["connection_status"] == "offline":
            body["connector_error"] = {"code": "DEVICE_OFFLINE", "retryable": True}
        return body

    return mcp


# ---------- the first read: list_devices → get_device_state for each ----------

def body(result) -> dict:
    """The tool's JSON result (structured content, or the JSON text block)."""
    structured = getattr(result, "structured_content", None) or getattr(result, "structuredContent", None)
    if structured:
        return structured
    return json.loads(result.content[0].text)


async def main() -> None:
    mock = "--mock" in sys.argv
    print(f"Devices: {'mock (in-process)' if mock else MCP_URL}\n")
    async with (Client(mock_server()) if mock else live_client()) as client:
        devices = body(await client.call_tool("list_devices", {}))["devices"]
        if not devices:
            print("No shared devices yet. In the Reachthings console check: (1) Devices: the device account is connected,")
            print("(2) the device is active for agents, (3) Agents > this agent: the device is shared. Then run this again.")
            return
        for d in devices:
            state = body(await client.call_tool("get_device_state", {"device_id": d["device_id"]}))
            values = []
            for a in state.get("attributes", []):
                if a["value"] is None:
                    values.append(f"{a['attribute']}: never reported")
                else:
                    values.append(f"{a['attribute']}: {a['value']}" + ("" if a["fresh"] else f" (stale, observed {a['observed_at']})"))
            note = f" Couldn't refresh ({state['connector_error']['code']}), last known values." if state.get("connector_error") else ""
            print(f"- {d['alias'] or d['kind']} ({d['connection_status']}): {', '.join(values) or 'no readable state'}.{note}")


if __name__ == "__main__":
    asyncio.run(main())
```

## 2. 동작 방식

1. 에이전트가 MCP 로 Reachthings 도구 목록을 받아 조회 도구(`list_devices`, `get_device`, `get_device_state`)를 모델에 넘깁니다.
2. 모델이 도구를 고르면 에이전트가 MCP 로 호출하고 결과를 모델에 돌려줍니다.
3. 모델은 `list_devices` 를 부른 뒤, 받은 `device_id` 마다 `get_device_state` 를 부릅니다.
4. 모델이 기기 이름과 관측된 값으로 답합니다. 제조사 토큰이나 계정은 모델에 보이지 않습니다.

```ts
// simplified from model.ts: the loop at the heart of the starter
const { tools: mcpTools } = await client.listTools();            // 1. Reachthings tools…
const tools = mcpTools.filter((t) => READ_TOOLS.includes(t.name))
  .map((t) => ({ name: t.name, description: t.description ?? "", input_schema: t.inputSchema }));
const messages = [{ role: "user", content: question }];
for (;;) {
  const turn = await model.create({ system: SYSTEM, tools, messages }); // 2. …go to the model
  messages.push({ role: "assistant", content: turn.content });
  const calls = turn.content.filter((b) => b.type === "tool_use");
  if (turn.stop_reason !== "tool_use") return text(turn);          // 4. final answer
  const results = [];
  for (const call of calls) {                                       // 3. run what it picked, over MCP
    const r = await client.callTool({ name: call.name, arguments: call.input });
    results.push({ type: "tool_result", tool_use_id: call.id, content: JSON.stringify(r.structuredContent ?? r.content) });
  }
  messages.push({ role: "user", content: results });               //    and send the results back
}
```

`model.ts` 의 시스템 프롬프트는 `fresh: false` 인 값은 오래된 값으로 `observed_at` 과 함께, `null` 은 보고된 적 없는 값으로, `connector_error` 는 새로 읽지 못한 이유로 말하게 합니다.

## 3. 내 기기로 확인

**직접** 표시가 있는 단계는 사람이 브라우저에서 합니다. 코딩 에이전트는 그 단계마다 멈추고 알려 줍니다.

1. **직접** · [Reachthings 콘솔](https://connect.reachthings.com/app)에 로그인합니다. 새 계정은 처음 실제 기기를 읽을 때 14일 체험이 시작되며 카드는 필요 없습니다.
2. **직접** · [기기 → 기기 추가](https://connect.reachthings.com/app/connections)에서 기기가 있는 계정(예: SmartThings)을 연결합니다. 새 기기는 요금제 한도 안에서 바로 에이전트용으로 활성화됩니다.
3. 스타터에 자기 클라이언트 ID 를 주세요(6단계): `/docs/oauth/starter-client.json` 을 복사해 `client_id` 를 게시할 HTTPS 주소로 바꾸고 `client_name` 도 바꾼 뒤(리디렉션 주소는 그대로) 그 주소에 게시하고, Reachthings 에 그 주소의 등록을 요청합니다([인증](https://developer.reachthings.com/docs/auth), 아직 셀프서비스가 아닙니다). 그다음 `RT_CLIENT_ID` 를 그 주소로 둡니다. 공용 스타터 ID 는 모의 기기용입니다. Reachthings 는 그 ID 를 쓰는 앱들을 구분할 수 없어 동의를 받지 않고 실제 기기를 읽지 않습니다. 다른 클라이언트 ID 로 저장된 토큰은 무시되므로 그냥 다시 로그인하면 됩니다.
4. `npm start` 를 실행합니다. 브라우저에 Reachthings 로그인 화면이 열리면 같은 계정으로 로그인하고 허용하세요. 브라우저가 `http://127.0.0.1:8976/callback` 으로 돌아오고 터미널이 이어서 진행합니다. 토큰은 `.reachthings-tokens.json` 에 저장됩니다(git 에 넣지 마세요).
5. **직접** · [에이전트](https://connect.reachthings.com/app/grants)에 내 클라이언트의 새 에이전트가 나타납니다. 열어서 앱의 운영 주체를 확인하고(동의에 적힙니다) 동의한 뒤, 기기를 고르고 **상태 조회만**를 허용하세요.
6. `npm start` 를 다시 실행합니다. 모의 기기 때와 같은 방식으로 내 기기의 이름과 관측된 상태를 답합니다.

> 스타터는 Reachthings 공용 스타터 클라이언트(`client_id` `https://developer.reachthings.com/docs/oauth/starter-client.json`)로 로그인합니다. 로그인 화면에 `invalid_request` 가 나오면 그 클라이언트가 아직 로그인 서버에 등록되지 않은 것으로, Reachthings 가 고칠 일입니다. 그때까지는 모의 기기로 진행하세요.

## 4. 기기가 없다고 답할 때

`list_devices` 는 연결돼 있고, 활성화돼 있고, 이 에이전트에 공유된 기기만 돌려줍니다. 이 순서로 확인하세요:

1. [기기](https://connect.reachthings.com/app/devices): 기기 계정이 연결됨으로 보이는지. **다시 연결**이 보이면 제조사에 다시 로그인하세요.
2. 기기: 기기가 **비활성**으로 표시돼 있지 않은지. 그렇다면 **활성화**를 누르세요(활성 기기 수는 요금제에 따라 정해집니다).
3. [에이전트](https://connect.reachthings.com/app/grants) → **Quickstart starter**(또는 내 에이전트): 기기가 공유돼 있고 **상태 조회만**가 허용돼 있는지.
4. 스타터에 로그인한 Reachthings 계정이 콘솔에서 쓰는 계정과 같은지.

그런 다음 `npm start` 를 다시 실행하세요. `401` 이 나오면 저장된 토큰이 더는 유효하지 않은 것입니다. `.reachthings-tokens.json` 을 지우고 다시 실행해 로그인하세요.

## 5. 내 프로젝트에 넣기

기존 에이전트로 옮길 것:

- `https://connect.reachthings.com/mcp` 에 Streamable HTTP 와 OAuth(Authorization Code + PKCE)로 붙는 MCP 클라이언트. TypeScript 는 `reachthings.ts` 처럼 `@modelcontextprotocol/sdk`, Python 은 `quickstart.py` 처럼 `mcp` 패키지를 씁니다.
- `model.ts` 처럼 `tools/list` 의 조회 도구를 모델에 주고 모델이 고른 도구를 실행합니다. 프로젝트에 이미 모델 SDK 와 도구 루프가 있으면 그것을 그대로 쓰세요.
- 먼저 `mock-reachthings.ts` 로 검증하세요. 도구 이름과 응답이 같은 MCP 서버를 프로세스 안에서 연결합니다.
- 토큰은 소스 코드와 로그에 남기지 마세요.

## 6. 내 앱의 client_id

Reachthings 로그인 서버는 앱을 **클라이언트 ID 메타데이터 문서**(CIMD)로 식별합니다. `client_id` 는 내가 게시한 작은 JSON 파일의 HTTPS 주소입니다. 클라이언트 시크릿과 동적 등록은 없습니다.

- **모의 기기로 개발할 때:** 스타터의 `client_id` 를 그대로 쓰세요. 콜백이 `http://127.0.0.1:8976/callback` 이므로 8976 포트를 비워 두세요.
- **내 앱, 그리고 실제 기기:** 아래와 같은 문서를 내 HTTPS 주소에 게시합니다. 문서 안의 `client_id` 는 정확히 그 주소여야 합니다. 그리고 Reachthings 에 등록을 요청합니다([인증](https://developer.reachthings.com/docs/auth), 아직 셀프서비스가 아닙니다). 공용 스타터 `client_id` 로는 모의 기기만 읽습니다.

`https://your-app.example.com/oauth/client.json`

```json
{
  "client_id": "https://your-app.example.com/oauth/client.json",
  "client_name": "Your agent",
  "client_uri": "https://your-app.example.com",
  "redirect_uris": [
    "http://127.0.0.1:8976/callback",
    "https://your-app.example.com/oauth/callback"
  ],
  "grant_types": [
    "authorization_code",
    "refresh_token"
  ],
  "response_types": [
    "code"
  ],
  "token_endpoint_auth_method": "none"
}
```

로그인 뒤 사용자 토큰에는 내 앱이 클라이언트로 들어가므로, 사용자는 콘솔에서 내 에이전트를 이름으로 보고 접근할 기기를 고릅니다. [인증](https://developer.reachthings.com/docs/auth)을 참고하세요.

## 7. 기기 제어(조회가 된 다음)

제어도 같은 방식이고 규칙이 하나 더 있습니다. **접수는 완료가 아닙니다.** `get_device` 가 이 에이전트에 허용된 동작으로 보여 준 것만 실행하고, `request_key` 와 함께 한 번 보낸 뒤, `next_action` 을 따라 **같은** `command_id` 를 상태가 끝날 때까지 확인합니다.

```bash
npm run control                 # mock: turn the mock AC on
npm run control -- --approval    # mock: an action that needs the owner's approval
```

```text
Living room AC: appliance.power.set {"power":"on"}
command cmd_mock_1: queued
command cmd_mock_1: dispatching
command cmd_mock_1: succeeded
Done: appliance.power.set succeeded (verified: state_observed).
```

```text
Front door: door.unlock {} (needs the owner's approval)
command cmd_mock_1: waiting_approval
Waiting for approval. Ask the owner to open: https://connect.reachthings.com/app/approvals/apr_cmd_mock_1
command cmd_mock_1: waiting_approval
command cmd_mock_1: queued
command cmd_mock_1: dispatching
command cmd_mock_1: succeeded
Done: door.unlock succeeded (verified: state_observed).
```

- `poll_command_status`: `next_poll_after_ms` 만큼 기다린 뒤 같은 `command_id` 로 `get_command_status` 를 부릅니다. 대기 호출 한 번이 끝난 것은 결과가 아닙니다.
- `open_approval_url`: 소유자에게 `approval.url` 을 보여 주고 계속 확인합니다. 링크를 여는 것만으로는 승인되지 않습니다.
- `show_result`: 최종 상태를 알립니다. 성공은 `succeeded` 일 때만 말합니다.
- `show_unknown`(`outcome_unknown`): 실행됐는지 알 수 없습니다. 자동으로 다시 보내지 마세요.

실제 기기에서는 에이전트 화면에서 그 동작을 허용한 뒤 `npm run control -- --live <device_id> <action> '<parameters JSON>'` 로 실행합니다. 동작에 `security_pin_registered` 같은 사전 조건이 있으면 실행하고 결과를 따르세요. PIN 미등록은 명령이 `PIN_NOT_REGISTERED` 를 돌려줄 때만 안내합니다. [명령 수명주기](https://developer.reachthings.com/docs/lifecycle)를 참고하세요.

## 8. Python

같은 첫 조회를 평범한 `.py` 파일 하나로: `list_devices` 뒤에 기기마다 `get_device_state`. Python 3.10 이상.

```bash
mkdir reachthings-py && cd reachthings-py
curl -fsSLO "https://developer.reachthings.com/docs/quickstart/starter/quickstart.py"
python3 -m venv .venv && . .venv/bin/activate
pip install "mcp==2.3.0"
python quickstart.py --mock
```

```text
Devices: mock (in-process)

- Living room AC (online): power: off, target_temperature: 24, current_temperature: 27.5.
- Desk lamp plug (offline): outlet_power: on (stale, observed 2026-11-15T10:59:36.653565+00:00). Couldn't refresh (DEVICE_OFFLINE), last known values.
```

`--mock` 없이 `python quickstart.py` 를 실행하면 TypeScript 스타터와 같은 방식(브라우저, 8976 포트 콜백)으로 로그인하고 공유한 기기를 읽습니다.

## 이미 쓰는 AI 도구에 연결하기

Claude, ChatGPT, Claude Code, Codex 같은 MCP 클라이언트는 같은 주소에 연결하고 OAuth 로 로그인합니다. 키를 붙여 넣을 일은 없습니다. 클라이언트별 설정과 확인 범위는 [MCP 클라이언트](https://developer.reachthings.com/docs/clients)에 있습니다.

Claude Code 는 `claude mcp add --transport http reachthings https://connect.reachthings.com/mcp` 를 실행하거나, 프로젝트의 `.mcp.json` 에 다음을 넣으세요:

`.mcp.json`

```json
{
  "mcpServers": {
    "reachthings": {
      "type": "http",
      "url": "https://connect.reachthings.com/mcp"
    }
  }
}
```

그다음 [에이전트](https://connect.reachthings.com/app/grants)에서 새 에이전트에 기기를 공유하고 “공유한 기기 상태 알려줘”라고 물어보세요.

## 다음

- [인증](https://developer.reachthings.com/docs/auth): 로그인, 범위(scope), 에이전트별 공유.
- [API 레퍼런스](https://developer.reachthings.com/docs/tools/overview): 모든 도구의 인자와 응답.
- [명령 수명주기](https://developer.reachthings.com/docs/lifecycle): 상태, next_action, 승인과 재시도.
- [get_command_status](https://developer.reachthings.com/docs/tools/get_command_status): command_id 로 명령 확인.
