Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(okx3d): serve endpoint-specific bazaar metadata in the 402 envelope

nirholas0a109050018b
diff --git a/api/_okx3d/discovery.js b/api/_okx3d/discovery.js
new file mode 100644
index 000000000..e631507a6
--- /dev/null
+++ b/api/_okx3d/discovery.js
@@ -0,0 +1,136 @@
+// Bazaar discovery + service metadata for the Agent Identity Studio A2MCP
+// endpoint (/api/okx/3d/identity-studio).
+//
+// The 402 envelope an unpaid caller receives carries this metadata, and buying
+// agents read its `bazaar` extension to learn how to call the service. Without
+// an endpoint-specific extension the envelope inherited build402Body's default,
+// which describes the main /api/mcp server: it told a buyer to call
+// `validate_model` with a `url` argument, a tool this server does not expose.
+// An agent that followed it would pay for create_identity and then send a call
+// the dispatcher rejects. Mirrors api/_mcp3d/discovery.js.
+
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { catalogEntry } from '../_lib/okx-catalog.js';
+
+const ENTRY = catalogEntry('identity-studio');
+
+export const RESOURCE_DESCRIPTION =
+ 'three.ws Agent Identity Studio, A2MCP (MCP Streamable HTTP) service that turns an AI ' +
+ "agent's brand brief into a complete 3D identity: rigged GLB avatar + posed studio renders " +
+ `with an OKX-avatar-slot PFP crop. $${ENTRY.priceUsd} per identity, USDC via x402; job ` +
+ 'status polling is free. Operated by three.ws.';
+
+// Endpoint-level v2 bazaar discovery entry, in the shape agentic.market's
+// validator expects (see api/_lib/x402-spec.js → bazaarExtension). Describes a
+// JSON-RPC 2.0 tools/call against THIS server's tools and the job handle that
+// comes back.
+function identityBazaarExtension() {
+ const exampleBody = {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: {
+ name: ENTRY.tool,
+ arguments: {
+ agent_name: 'Atlas',
+ brief: 'a calm, precise research agent with a cobalt-and-steel look',
+ },
+ },
+ };
+ const exampleResponse = {
+ jsonrpc: '2.0',
+ id: 1,
+ result: {
+ content: [
+ {
+ type: 'text',
+ text: 'Identity job accepted. Poll identity_status with this job_id until status is "done" (ETA ~3-6 min). job_id: idj_abc123',
+ },
+ ],
+ structuredContent: {
+ ok: true,
+ job_id: 'idj_abc123',
+ status: 'queued',
+ stage: 'generation',
+ eta_seconds: 300,
+ poll_tool: 'identity_status',
+ },
+ },
+ };
+ const requestBodySchema = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['jsonrpc', 'method'],
+ properties: {
+ jsonrpc: { type: 'string', const: '2.0' },
+ id: { type: ['string', 'number'] },
+ method: {
+ type: 'string',
+ enum: ['initialize', 'tools/list', 'tools/call', 'ping'],
+ description: 'MCP JSON-RPC method.',
+ },
+ params: {
+ type: 'object',
+ description:
+ `For tools/call: { name, arguments }. Tool names: ${ENTRY.tool} (paid, $${ENTRY.priceUsd}), ` +
+ 'identity_status (free job polling), getting_started (free overview). See tools/list.',
+ },
+ },
+ };
+ const responseBodySchema = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ jsonrpc: { type: 'string', const: '2.0' },
+ id: { type: ['string', 'number'] },
+ result: {
+ type: 'object',
+ properties: {
+ content: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['type', 'text'],
+ properties: {
+ type: { type: 'string', enum: ['text'] },
+ text: { type: 'string' },
+ },
+ },
+ },
+ },
+ },
+ error: {
+ type: 'object',
+ properties: { code: { type: 'number' }, message: { type: 'string' } },
+ },
+ },
+ };
+ return {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'POST', body: exampleBody, bodyType: 'json' },
+ output: { type: 'json', example: exampleResponse },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodyType: 'json',
+ bodySchema: requestBodySchema,
+ outputSchema: responseBodySchema,
+ }),
+ };
+}
+
+// The challenge override threaded into authenticateRequest/handleSse so the 402
+// envelope advertises Identity Studio metadata and discovery instead of the
+// shared MCP defaults. `tags` is capped at 5 by the Bazaar spec (withService
+// truncates silently), so "okx" earns its slot here, this surface exists to be
+// found on OKX.AI.
+export const IDENTITY_CHALLENGE = {
+ description: RESOURCE_DESCRIPTION,
+ bazaar: identityBazaarExtension(),
+ ...withService({
+ serviceName: 'three.ws Agent Identity Studio',
+ tags: ['x402', 'mcp', '3d', 'identity', 'okx'],
+ }),
+};
diff --git a/api/_okx3d/tools.js b/api/_okx3d/tools.js
index bb5bc2819..fb8e2cd5b 100644
--- a/api/_okx3d/tools.js
+++ b/api/_okx3d/tools.js
@@ -1,13 +1,13 @@
-// Agent Identity Studio, MCP tool catalog, dispatcher, pricing, and 402
-// challenge metadata for the /api/okx/3d/identity-studio A2MCP endpoint.
-// Prices and descriptions come from api/_lib/okx-catalog.js (single source of
-// truth shared with the free catalog service and the OKX listing).
+// Agent Identity Studio, MCP tool catalog, dispatcher, and pricing for the
+// /api/okx/3d/identity-studio A2MCP endpoint. Prices and descriptions come from
+// api/_lib/okx-catalog.js (single source of truth shared with the free catalog
+// service and the OKX listing); the 402 challenge metadata lives next door in
+// ./discovery.js.
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import { makeDispatcher, PROTOCOL_VERSION } from '../_lib/mcp-dispatch.js';
import { buildGettingStartedTool, GETTING_STARTED_TOOL } from '../_lib/mcp-getting-started.js';
-import { withService } from '../_lib/x402/bazaar-helpers.js';
import { catalogEntry } from '../_lib/okx-catalog.js';
import {
createIdentityJob,
@@ -164,16 +164,3 @@ export const dispatch = makeDispatcher({
tools: TOOLS,
logName: 'mcp-okx-identity',
});
-
-// 402 challenge metadata: how facilitators/indexers see this endpoint.
-export const IDENTITY_CHALLENGE = {
- description:
- 'three.ws Agent Identity Studio, A2MCP (MCP Streamable HTTP) service that turns an AI ' +
- "agent's brand brief into a complete 3D identity: rigged GLB avatar + posed studio renders " +
- `with an OKX-avatar-slot PFP crop. $${ENTRY.priceUsd} per identity, USDC via x402; job ` +
- 'status polling is free. Operated by three.ws.',
- ...withService({
- serviceName: 'three.ws Agent Identity Studio',
- tags: ['x402', 'mcp', '3d', 'avatar', 'identity', 'okx'],
- }),
-};
diff --git a/api/okx/3d/[service].js b/api/okx/3d/[service].js
index 8b97d56d3..bfb871f1c 100644
--- a/api/okx/3d/[service].js
+++ b/api/okx/3d/[service].js
@@ -58,8 +58,8 @@ import {
PROTOCOL_VERSION,
identityX402Amount,
isPublicIdentityTool,
- IDENTITY_CHALLENGE,
} from '../../_okx3d/tools.js';
+import { IDENTITY_CHALLENGE } from '../../_okx3d/discovery.js';
import { invokeRestService, isRestPaidService } from '../../_okx3d/rest-services.js';
const BASE = 'https://three.ws';
@@ -85,14 +85,21 @@ async function probe(name, fn) {
async function healthReport() {
const subsystems = await Promise.all([
probe('generation', async () => {
- // /api/forge serves its catalog/config on GET without starting a job,
- // reachable + parseable proves the generation front door is up.
- const res = await fetch(`${BASE}/api/forge`, {
+ // ?catalog is the tier + backend matrix /api/forge serves without
+ // starting a job. A bare GET /api/forge answers 400 missing_job, which
+ // a broken generation lane returns just as happily, so probe the
+ // payload that actually proves the front door is up: reachable, and
+ // carrying at least one tier and one backend.
+ const res = await fetch(`${BASE}/api/forge?catalog`, {
headers: { accept: 'application/json' },
signal: AbortSignal.timeout(10_000),
});
- if (res.status >= 500) throw new Error(`forge returned ${res.status}`);
- return { status: res.status };
+ if (!res.ok) throw new Error(`forge catalog returned ${res.status}`);
+ const catalog = await res.json();
+ const tiers = Array.isArray(catalog?.tiers) ? catalog.tiers.length : 0;
+ const backends = Array.isArray(catalog?.backends) ? catalog.backends.length : 0;
+ if (!tiers || !backends) throw new Error('forge catalog empty');
+ return { tiers, backends };
}),
probe('render', async () => {
const res = await fetch(`${BASE}/api/render/avatar-clip`, {
@@ -145,6 +152,31 @@ async function healthReport() {
return { ok: subsystems.every((s) => s.ok), subsystems, checkedAt: new Date().toISOString() };
}
+// /health is free and unauthenticated, and one call fans out to five
+// subsystems (three HTTP probes, an R2 head, an X Layer RPC read). Memoize the
+// report briefly and let concurrent callers share the in-flight probe, so a
+// poll loop costs the subsystems one sweep per window instead of one per
+// request. Same shape /api/forge?health uses. `checkedAt` in the body tells the
+// caller how old the reading is.
+const HEALTH_TTL_MS = 30_000;
+let healthMemo = { at: 0, report: null };
+let healthInFlight = null;
+
+async function cachedHealthReport() {
+ if (healthMemo.report && Date.now() - healthMemo.at < HEALTH_TTL_MS) return healthMemo.report;
+ if (!healthInFlight) {
+ healthInFlight = healthReport()
+ .then((report) => {
+ healthMemo = { at: Date.now(), report };
+ return report;
+ })
+ .finally(() => {
+ healthInFlight = null;
+ });
+ }
+ return healthInFlight;
+}
+
// Per-service accepts: the OKX X Layer entry leads (that is the rail this
// surface exists for, the buyer CLI auto-selects the first `exact` entry),
// followed by the platform's existing rails so non-OKX agents can pay too.
@@ -358,6 +390,19 @@ async function handleIdentityStudio(req, res) {
const batch = Array.isArray(body) ? body : [body];
if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');
+ // The JSON-RPC ids of the PAID calls in this batch. Settlement is judged on
+ // these responses alone: in a mixed batch (initialize + create_identity), a
+ // blanket "did anything succeed" charged the buyer the full identity price
+ // when create_identity failed validation but the free message beside it
+ // answered fine. Priced notifications carry no id, so an empty set falls
+ // back to judging the whole batch.
+ const pricedIds = new Set(
+ batch
+ .filter((m) => m?.method === 'tools/call' && identityX402Amount(m?.params?.name))
+ .map((m) => m?.id)
+ .filter((id) => id !== undefined && id !== null),
+ );
+
// Single-use lock on the payment proof across dispatch+settle, mirroring
// /api/mcp-3d, a replayed X-PAYMENT can't run a second job before the
// first settle lands.
@@ -385,7 +430,8 @@ async function handleIdentityStudio(req, res) {
// the payment is never settled, the pay-only-on-acceptance promise the
// catalog description makes.
if (x402Ctx) {
- const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));
+ const judged = pricedIds.size ? responses.filter((r) => r && pricedIds.has(r.id)) : responses;
+ const anySuccess = judged.some((r) => r && !r.error && !(r.result && r.result.isError));
if (anySuccess) {
try {
const settled = await settlePayment({ verified: x402Ctx.verified });
@@ -425,8 +471,13 @@ export default wrap(async (req, res) => {
if (service === 'health') {
if (req.method !== 'GET' && req.method !== 'HEAD')
return json(res, 405, { error: 'method_not_allowed', message: 'health is GET-only' });
- const report = await healthReport();
- return json(res, report.ok ? 200 : 503, report, { 'cache-control': 'no-store' });
+ const report = await cachedHealthReport();
+ // A green reading is edge-cacheable for the memo window; a red one is
+ // not, so recovery shows up on the next request instead of waiting out a
+ // CDN entry.
+ return json(res, report.ok ? 200 : 503, report, {
+ 'cache-control': report.ok ? 'public, max-age=15, s-maxage=30' : 'no-store',
+ });
}
if (service === 'identity-studio') return handleIdentityStudio(req, res);