# Connect devices to your agent

Two ways to start. Building an agent? Start with the first: a starter you can run in two minutes with mock devices, then with your own.

Source: https://developer.reachthings.com/docs/quickstart · 한국어: https://developer.reachthings.com/docs/quickstart.ko.md

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

**Pick a path**

1. [Build into my own agent](#build): Let users ask “What’s the status of my devices?” and get an answer from the devices they’ve shared.
2. [Connect an AI tool I already use](#ai-tools): Connect Reachthings to Claude, ChatGPT, Claude Code, Codex, or another supported client to read your shared devices.

## Build into my own agent

Working in a coding agent such as Claude Code or Codex? Give it this page and one sentence. It finds what it needs here, tests with mock devices first, and tells you when it needs you to sign in or share a device.

**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.

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

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

Doing it by hand? Follow the steps below; they're the same ones your coding agent follows. What you need: Node 20 or later and npm. No account is needed until step 3.

## 1. Run the starter with mock devices

The starter is a small TypeScript agent. With mock devices it runs entirely on your computer: the mock server has the same tool names and response shapes as Reachthings, and without an `ANTHROPIC_API_KEY` a scripted stand-in plays the model so the whole loop still runs.

```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
```

Expected output (times differ):

```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.
```

Each device is answered with its name and the values it reported. A stale value says when it was observed, a value the device never reported says so, and an offline device returns its last known values with the reason.

No shared devices? `npm run mock -- --empty` shows what the agent says then:

```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.
```

To use Claude as the model, set `ANTHROPIC_API_KEY` (and optionally `ANTHROPIC_MODEL`, default `claude-sonnet-5-5`) and run `npm run mock` again. The tool calls are the same; the answer is written by the model.

### All starter files

Each file is also at `https://developer.reachthings.com/docs/quickstart/starter/<file>`.

#### 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. How it works

1. The agent lists the Reachthings tools over MCP and gives the read tools (`list_devices`, `get_device`, `get_device_state`) to the model.
2. The model picks a tool. The agent calls it over MCP and sends the result back.
3. The model calls `list_devices`, then `get_device_state` with each `device_id` it got back.
4. The model answers with device names and observed values. It never sees a manufacturer token or account.

```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
}
```

The system prompt in `model.ts` tells the model to report `fresh: false` values as stale with their `observed_at`, a `null` value as never reported, and a `connector_error` as the reason it couldn't refresh.

## 3. Use your own devices

Steps marked **You** are done by a person in the browser. A coding agent stops and asks you at each one.

1. **You** · Sign in to the [Reachthings console](https://connect.reachthings.com/app). A new account starts a 14-day trial when it first reads a real device; no card needed.
2. **You** · [Devices → Add devices](https://connect.reachthings.com/app/connections): connect the account your devices live in (for example SmartThings). New devices are active for agents right away, within your plan's limit.
3. Give the starter its own client ID (step 6): copy `/docs/oauth/starter-client.json`, set its `client_id` to the HTTPS URL where you will publish it and change `client_name` (keep the redirect URI), publish it there, and ask Reachthings to register that URL ([Authentication](https://developer.reachthings.com/docs/auth); registration isn't self-serve yet). Then set `RT_CLIENT_ID` to the URL. The shared starter ID is for the mock only: Reachthings cannot tell apps using it apart, so it takes no consent and reads no real devices. A token saved for another client ID is ignored, so you simply sign in again.
4. Run `npm start`. Your browser opens the Reachthings sign-in page; sign in with the same account and allow access. The browser returns to `http://127.0.0.1:8976/callback` and the terminal continues. The token is saved in `.reachthings-tokens.json` (keep it out of git).
5. **You** · [Agents](https://connect.reachthings.com/app/grants): a new agent for your client appears. Open it, confirm who operates the app (the consent names it), agree, then pick the devices and allow **See status**.
6. Run `npm start` again. The agent answers with your devices' names and observed state, the same way as with the mock.

> The starter signs in with Reachthings' shared starter client (`client_id` `https://developer.reachthings.com/docs/oauth/starter-client.json`). If the sign-in page says `invalid_request`, that client isn't registered on the sign-in server yet; that's on Reachthings, not you. Keep using the mock until then.

## 4. If the answer says there are no devices

`list_devices` returns only devices that are connected, active and shared with this agent. Check, in this order:

1. [Devices](https://connect.reachthings.com/app/devices): the device account shows as connected. If it says **Reconnect**, sign in to the manufacturer again.
2. Devices: the device isn't marked **Not active**. If it is, choose **Activate** (your plan limits how many are active).
3. [Agents](https://connect.reachthings.com/app/grants) → **Quickstart starter** (or your agent): the device is shared with **See status** allowed.
4. You signed in to the starter with the same Reachthings account you use in the console.

Then run `npm start` again. A `401` means the saved token is no longer valid: delete `.reachthings-tokens.json` and run it again to sign in.

## 5. Add it to your own project

What to carry over from the starter into an existing agent:

- An MCP client for `https://connect.reachthings.com/mcp` over Streamable HTTP with OAuth (Authorization Code + PKCE). In TypeScript that's `@modelcontextprotocol/sdk`, as in `reachthings.ts`; in Python, the `mcp` package, as in `quickstart.py`.
- Give your model the read tools from `tools/list` and run the ones it picks, as in `model.ts`. Keep your project's existing model SDK and loop if it has one.
- Test against `mock-reachthings.ts` first: it is an MCP server with the same tool names and responses, connected in-process.
- Keep tokens out of source code and logs.

## 6. Your app's client_id

Reachthings' sign-in server identifies apps by a **client ID metadata document** (CIMD): the `client_id` is the HTTPS URL of a small JSON file you publish. There is no client secret and no dynamic registration.

- **Developing with the mock:** use the starter's `client_id` as is. Its callback is `http://127.0.0.1:8976/callback`, so keep port 8976 free.
- **Your own app, and any real device:** publish a document like the one below at your own HTTPS URL — its `client_id` must be exactly that URL — and ask Reachthings to register it (see [Authentication](https://developer.reachthings.com/docs/auth); registration isn't self-serve yet). The shared starter `client_id` reads mock devices only.

`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"
}
```

After sign-in your users' tokens carry your app as the client, so in the console they see your agent by name and choose what it can reach. See [Authentication](https://developer.reachthings.com/docs/auth).

## 7. Control a device (after reading works)

Control follows the same pattern, with one rule: **accepted is not done**. Run an action only if `get_device` lists it for this agent, send it once with a `request_key`, then follow `next_action` and check the **same** `command_id` until the status is final.

```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`: wait `next_poll_after_ms`, then call `get_command_status` with the same `command_id`. One finished wait is not a result.
- `open_approval_url`: show the owner `approval.url` and keep checking. Opening the link alone approves nothing.
- `show_result`: report the final status. Print success only for `succeeded`.
- `show_unknown` (`outcome_unknown`): it may or may not have run. Don't resend automatically.

On real devices: `npm run control -- --live <device_id> <action> '<parameters JSON>'`, after you allow that action for the agent under Agents. If an action lists a precondition such as `security_pin_registered`, run it and follow the result; mention a missing PIN only when the command returns `PIN_NOT_REGISTERED`. See [Command lifecycle](https://developer.reachthings.com/docs/lifecycle).

## 8. Python

The same first read in one plain `.py` file: `list_devices`, then `get_device_state` for each device. Python 3.10 or later.

```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.
```

`python quickstart.py` without `--mock` signs in the same way as the TypeScript starter (browser, callback on port 8976) and reads your shared devices.

## Connect an AI tool I already use

Claude, ChatGPT, Claude Code, Codex and other MCP clients connect to the same URL and sign in with OAuth; you never paste a key. Step-by-step setup and how well each client is tested: [MCP clients](https://developer.reachthings.com/docs/clients).

For Claude Code, run `claude mcp add --transport http reachthings https://connect.reachthings.com/mcp`, or put this in `.mcp.json` in your project:

`.mcp.json`

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

Then share devices with the new agent under [Agents](https://connect.reachthings.com/app/grants) and ask “What’s the status of my shared devices?”.

## Next

- [Authentication](https://developer.reachthings.com/docs/auth): sign-in, scopes and per-agent sharing.
- [API reference](https://developer.reachthings.com/docs/tools/overview): every tool with arguments and responses.
- [Command lifecycle](https://developer.reachthings.com/docs/lifecycle): statuses, next_action, approval and retries.
- [get_command_status](https://developer.reachthings.com/docs/tools/get_command_status): checking a command by its command_id.
