Doramagic Project Pack · Human Manual

justoneapi-mcp

JustOneAPI MCP Server is a Model Context Protocol (MCP) server that exposes JustOneAPI endpoints to AI assistants like Claude Desktop, Cursor, and other MCP-compatible hosts. The server ac...

Getting Started with JustOneAPI MCP

Related topics: Authentication, MCP Host Integration

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Components

Continue reading this section for the full explanation and source context.

Section Technology Stack

Continue reading this section for the full explanation and source context.

Section Option 1: npx (Recommended)

Continue reading this section for the full explanation and source context.

Related topics: Authentication, MCP Host Integration

Getting Started with JustOneAPI MCP

Overview

JustOneAPI MCP Server is a Model Context Protocol (MCP) server that exposes JustOneAPI endpoints to AI assistants like Claude Desktop, Cursor, and other MCP-compatible hosts. The server acts as a thin transport layer that handles authentication, retries, timeouts, and error normalization while returning raw JSON responses from upstream platforms.

Key Characteristics:

  • Returns unmodified upstream JSON responses for maximum data fidelity
  • No field parsing or schema normalization
  • Designed for AI agents and developer workflows
  • Supports multiple Chinese social media and news platforms

Sources: README.md:1-20

Architecture

System Components

graph TD
    A[MCP Host<br/>Claude Desktop/Cursor] --> B[JustOneAPI MCP Server]
    B --> C[JustOneAPI REST API]
    C --> D[Upstream Platforms]
    
    D --> E[Weibo]
    D --> F[WeChat]
    D --> G[Zhihu]
    D --> H[Douyin]
    D --> I[Xiaohongshu]
    D --> J[Bilibili]
    D --> K[Kuaishou]
    D --> L[News]
    
    B --> M[Authentication]
    B --> N[Retry Logic]
    B --> O[Error Normalization]

Technology Stack

ComponentTechnologyVersion
RuntimeNode.js>= 18.0.0
MCP SDK@modelcontextprotocol/sdk^1.25.1
ValidationZod^4.3.4
Environmentdotenv^17.2.3
LanguageTypeScript^5.9.3

Sources: package.json:18-26

Prerequisites

Before using JustOneAPI MCP, ensure you have:

  1. Node.js 18.0.0 or higher installed
  2. JustOneAPI Token obtained from justoneapi.com
  3. MCP-compatible host (Claude Desktop, Cursor, or other)

Installation

The simplest method requires no installation. Configure your MCP host to run the package directly via npx.

Sources: README.md:85-95

Option 2: Local Installation

For production environments, install the package locally:

npm install -g justoneapi-mcp

Configuration

Claude Desktop Configuration

Edit the configuration file for your operating system:

OSConfiguration Path
macOS~/Library/Application Support/Claude/claude_desktop_config.json
Windows%APPDATA%\Claude\claude_desktop_config.json
Linux~/.config/Claude/claude_desktop_config.json

Configuration Example:

{
  "mcpServers": {
    "justoneapi": {
      "command": "npx",
      "args": ["-y", "justoneapi-mcp"],
      "env": {
        "JUSTONEAPI_TOKEN": "your_actual_token_here"
      }
    }
  }
}

Sources: README.md:85-102

Environment Variables

VariableRequiredDefaultDescription
JUSTONEAPI_TOKENYes-Your JustOneAPI authentication token
JUSTONEAPI_BASE_URLNohttps://api.justoneapi.comAPI endpoint URL
JUSTONEAPI_TIMEOUT_MSNo20000Request timeout in milliseconds
JUSTONEAPI_RETRYNo1Number of retries after first attempt
JUSTONEAPI_DEBUGNofalseEnable debug logging to stderr

Sources: README.md:138-147

Available Tools

Tool Naming Convention

All tools follow the pattern: {platform}_{action}_{version}

Current Tools

ToolDescriptionVersion
unified_search_v1Unified search across multiple platformsv1
kuaishou_search_video_v2Platform-specific video searchv2

Sources: README.md:55-58

Search across multiple Chinese social media and news platforms in a single request.

Supported Platforms:

  • Weibo
  • WeChat
  • Zhihu
  • Douyin
  • Xiaohongshu
  • Bilibili
  • Kuaishou
  • News (aggregated)

Sources: README.md:36-37

Parameters

ParameterTypeRequiredDescription
keywordstringYesSearch keyword with advanced syntax
sourcestringNoPlatform filter (default: ALL)
startstringFirst page onlyStart time yyyy-MM-dd HH:mm:ss (UTC+8)
endstringFirst page onlyEnd time yyyy-MM-dd HH:mm:ss (UTC+8)
nextCursorstringPagination onlyCursor from previous response

Sources: TOOLS.md:21-28

Search Syntax

graph LR
    A[Search Input] --> B{Syntax Type}
    B --> C[Single: deepseek]
    B --> D[AND: deepseek chatgpt]
    B --> E[OR: deepseek~chatgpt]
    B --> F[NOT: deepseek -chatgpt]
SyntaxExampleDescription
Single keyworddeepseekSimple search
AND searchdeepseek chatgptBoth keywords must appear
OR searchdeepseek~chatgptEither keyword can appear
NOT searchdeepseek -chatgptExclude keyword

Sources: README.md:48-55

Platform Options

ValueDescription
ALLSearch all platforms (default)
NEWSNews articles only
WEIBOWeibo posts
WEIXINWeChat public accounts
ZHIHUZhihu Q&A
DOUYINDouyin videos
XIAOHONGSHUXiaohongshu posts
BILIBILIBilibili videos
KUAISHOUKuaishou videos

Sources: src/tools/search/unified_search_v1.ts:12-19

Usage Examples

Natural Language Queries

Simply ask your MCP host to perform searches:

Search for "AI" discussions on Chinese social media from last week
Find posts about deepseek on Weibo from January 1st to 5th
Search for chatgpt OR 机器学习 on all platforms, exclude 广告

Code-Level Usage

First Page Request:

{
  "keyword": "AI",
  "source": "ALL",
  "start": "2025-01-01 00:00:00",
  "end": "2025-01-02 23:59:59"
}

Pagination Request:

{
  "keyword": "AI",
  "nextCursor": "eyJsYXN0SWQiOiIxMjM0NTY3ODkwIn0="
}

Sources: README.md:40-46

Response Format

All tools return raw JSON from upstream APIs without modification.

Success Response

{
  "code": 0,
  "message": null,
  "recordTime": "2025-12-31T14:55:21Z",
  "data": {
    // Platform-specific data structure
  }
}
FieldTypeDescription
codeinteger0 indicates success, non-zero indicates error
messagestring/nullError message if applicable
recordTimestringISO timestamp of the response
dataobjectPlatform-specific payload

Error Response

ERROR[ERROR_CODE] (upstream=XXX): Human-readable message

Sources: README.md:60-75

Error Handling

The MCP normalizes all errors into stable MCP error codes.

Error Codes Reference

Error CodeDescriptionRecommended Action
INVALID_TOKENToken is invalid or inactiveUpdate JUSTONEAPI_TOKEN
COLLECT_FAILEDData collection failedRetry after a short delay
RATE_LIMITEDToo many requestsSlow down and retry later
DAILY_QUOTA_EXCEEDEDDaily usage limit reachedWait until tomorrow or upgrade plan
INSUFFICIENT_BALANCEAccount balance too lowTop up your account
PERMISSION_DENIEDNo access to this resourceContact support
VALIDATION_ERRORInvalid request parametersCheck input values
INTERNAL_ERRORServer errorRetry later
NETWORK_TIMEOUTRequest timed outCheck network or retry
NETWORK_ERRORNetwork connection failedCheck internet connection
UPSTREAM_ERRORUnspecified upstream errorRetry or contact support

Sources: README.md:109-130

Error Format Example

ERROR[RATE_LIMITED] (upstream=302): Rate limit exceeded. Please slow down and retry later.

Sources: README.md:132-134

Pagination

When search results have more pages, responses include a nextCursor field.

How to Paginate

Simply ask for more results:

  • "Show me the next page of results"
  • "Get more results from the previous search"
  • "Continue with the next page"

The MCP host automatically:

  1. Extracts the nextCursor from the previous response
  2. Uses it to fetch the next page
  3. Continues until no more results are available

Note: When using nextCursor for pagination, you don't need to provide start, end, or source again—the cursor already contains this information.

Sources: README.md:76-95

Design Philosophy

Transport, Not Transformation

JustOneAPI MCP prioritizes:

  • Stability — Minimal abstraction over upstream APIs
  • Transparency — Raw data fidelity without modification
  • Compatibility — Long-term compatibility through unchanged responses

What This MCP Does

  • Exposes JustOneAPI endpoints as MCP tools
  • Handles authentication, retries, timeouts, and error normalization
  • Returns raw upstream JSON without field parsing
  • Designed for AI agents and developer workflows

What This MCP Does NOT Do

  • No field parsing or schema normalization
  • No data restructuring
  • No assumptions about upstream response structure

Sources: README.md:10-24

Advanced Configuration

Complete Configuration Example

{
  "mcpServers": {
    "justoneapi": {
      "command": "npx",
      "args": ["-y", "justoneapi-mcp"],
      "env": {
        "JUSTONEAPI_TOKEN": "your_token_here",
        "JUSTONEAPI_TIMEOUT_MS": "30000",
        "JUSTONEAPI_DEBUG": "true"
      }
    }
  }
}

Retry Behavior

The HTTP client implements automatic retry for:

  • Timeout errors (AbortError)
  • HTTP 5xx responses
  • Network failures (ECONNRESET, ECONNREFUSED, ENOTFOUND)
AttemptDelay
1Immediate
2250ms backoff
3+250ms × attempt

Sources: src/common/http.ts:30-40

Discovery and Verification

Listing Available Tools

In Claude Desktop:

Please list all available tools from justoneapi-mcp

In Cursor or other MCP hosts:

Use your host's tool discovery feature to see all available tools and their parameters.

Each tool includes:

  • Complete parameter descriptions
  • Input validation with Zod schemas
  • Detailed error messages
  • Example values in parameter descriptions

Sources: README.md:30-38

Next Steps

After setup:

  1. Obtain an API token from justoneapi.com
  2. Configure your MCP host with the token
  3. Try the unified search with a simple query
  4. Explore pagination for large result sets
  5. Review error codes for troubleshooting

License

MIT License

Sources: README.md:152

External Resources

Sources: README.md:1-20

Authentication

Related topics: Getting Started with JustOneAPI MCP, Configuration Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Environment Variables

Continue reading this section for the full explanation and source context.

Section Token Configuration File

Continue reading this section for the full explanation and source context.

Section Startup Validation

Continue reading this section for the full explanation and source context.

Related topics: Getting Started with JustOneAPI MCP, Configuration Reference

Authentication

Overview

The justoneapi-mcp server implements a token-based authentication mechanism for securing API access to the JustOneAPI platform. All requests to upstream APIs are authenticated using a bearer-style token passed via query parameters. The authentication system performs early validation at startup and before each API call to ensure credentials are present and properly configured.

The authentication layer serves as the gatekeeper for all MCP tools, including unified_search_v1 and kuaishou_search_video_v2. It validates the token's presence, encodes it safely for transmission, and provides clear error messages when authentication fails.

Architecture

graph TD
    A[MCP Host Request] --> B{Token Present?}
    B -->|No| C[Startup Validation<br/>src/index.ts:45-52]
    B -->|Yes| D[requireToken Call]
    
    D --> E{Token Valid?}
    E -->|Empty/Whitespace| F[INVALID_TOKEN Error]
    E -->|Valid| G[Encode Token]
    
    G --> H[Append to Query Params]
    H --> I[HTTP Request via getJson]
    
    I --> J{Response Code = 0?}
    J -->|Yes| K[Return Data]
    J -->|No| L[Error Mapping<br/>src/common/errors.ts]
    
    style F fill:#ffcccc
    style K fill:#ccffcc

Configuration

Environment Variables

Authentication is configured through environment variables in the MCP server configuration.

VariableRequiredDefaultDescription
JUSTONEAPI_TOKENYesYour JustOneAPI authentication token
JUSTONEAPI_BASE_URLNohttps://api.justoneapi.comAPI endpoint base URL
JUSTONEAPI_TIMEOUT_MSNo20000Request timeout in milliseconds
JUSTONEAPI_RETRYNo1Number of retries after initial attempt
JUSTONEAPI_DEBUGNofalseEnable debug logging to stderr

Token Configuration File

The token configuration is managed in src/common/config.ts.

// src/common/config.ts:1-15
export function requireToken(): string {
  const token = process.env.JUSTONEAPI_TOKEN;
  if (!token || !token.trim()) {
    throw new Error(
      "JUSTONEAPI_TOKEN environment variable is required. " +
        "Get your token at https://justoneapi.com"
    );
  }
  return token;
}

The requireToken() function validates that the token exists and is not empty or whitespace-only. If validation fails, it throws an error with instructions for obtaining a token. Sources: src/common/config.ts:1-15

Startup Validation

The server performs authentication validation during startup to fail fast if credentials are missing.

// src/index.ts:45-52
async function main() {
  // Validate configuration on startup
  if (!process.env.JUSTONEAPI_TOKEN?.trim()) {
    console.error(
      "[justoneapi-mcp] ERROR: JUSTONEAPI_TOKEN is required but not set.\n" +
        "Please set the JUSTONEAPI_TOKEN environment variable in your MCP host configuration"
    );
    process.exit(1);
  }
  // ... continue with server initialization
}

Sources: src/index.ts:45-52

Token Transmission

Query Parameter Encoding

Tokens are transmitted via URL query parameters for all API requests. The token is URL-encoded to handle special characters safely.

// src/tools/search/unified_search_v1.ts:35-36
export async function unifiedSearchV1(input: z.infer<typeof UnifiedSearchV1Input>) {
  const token = encodeURIComponent(requireToken());
  const keyword = encodeURIComponent(input.keyword);
  
  // Build query parameters
  const params = new URLSearchParams();
  params.append("token", token);
  params.append("keyword", keyword);
  // ...
}

Sources: src/tools/search/unified_search_v1.ts:35-36

HTTP Request Flow

All authenticated requests flow through the getJson() helper in src/common/http.ts.

sequenceDiagram
    participant MCP as MCP Host
    participant Server as justoneapi-mcp
    participant API as JustOneAPI
    
    MCP->>Server: Tool Request
    Server->>Server: requireToken()
    Note over Server: Validate token exists
    Server->>Server: getJson(pathWithQuery)
    Server->>API: GET with token in query
    API-->>Server: JSON Response
    Server->>Server: Check response.code
    alt code != 0
        Server->>Server: toMcpErrorPayload()
    end
    Server-->>MCP: Result or Error

The getJson() function includes the following security and reliability features:

FeatureImplementationPurpose
Early token validationrequireToken() at startFail fast on missing credentials
Timeout handlingAbortControllerPrevent hanging requests
Automatic retryConfigurable via JUSTONEAPI_RETRYHandle transient failures
Safe loggingtoSafeUrlForLog()Mask tokens in debug output
// src/common/http.ts:40-55
export async function getJson(pathWithQuery: string): Promise<UpstreamResponse> {
  // ensure token exists early (so we can return INVALID_TOKEN)
  requireToken();

  const url = `${config.baseUrl}${pathWithQuery}`;

  const attempts = 1 + Math.max(0, Number.isFinite(config.retry) ? config.retry : 0);
  let lastErr: ApiError | unknown;

  for (let attempt = 1; attempt <= attempts; attempt++) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), config.timeoutMs);
    // ...
  }
}

Sources: src/common/http.ts:40-55

Error Handling

When authentication fails, the server returns normalized MCP error codes.

Error CodeUpstream EquivalentDescriptionResolution
INVALID_TOKENToken missing or invalidUpdate JUSTONEAPI_TOKEN
RATE_LIMITED302Too many requestsSlow down and retry
DAILY_QUOTA_EXCEEDEDUsage limit reachedWait or upgrade plan
INSUFFICIENT_BALANCEAccount balance lowTop up account

Error Mapping

The mapUpstreamCode() function in src/common/errors.ts maps upstream error codes to MCP error codes.

// src/common/errors.ts:1-30
function mapUpstreamCode(code: number): JOAErrorCode {
  switch (code) {
    case 10001:
      return "INVALID_TOKEN";
    case 10002:
      return "INSUFFICIENT_BALANCE";
    case 10003:
      return "PERMISSION_DENIED";
    // ... other mappings
    default:
      return "UPSTREAM_ERROR";
  }
}

Sources: src/common/errors.ts:1-30

Error Payload Construction

// src/common/errors.ts:60-75
export function toMcpErrorPayload(e: unknown): {
  code: JOAErrorCode;
  message: string;
  upstreamCode?: number;
  httpStatus?: number;
} {
  const error = e as {
    name?: string;
    message?: string;
    upstreamCode?: number;
    httpStatus?: number;
    code?: string;
    cause?: unknown;
  };
  
  // Timeout from AbortController
  if (error.name === "AbortError") {
    return { code: "NETWORK_TIMEOUT", message: buildUserMessage("NETWORK_TIMEOUT") };
  }

  // Our own thrown upstreamCode (business code)
  if (error.upstreamCode !== undefined) {
    const upstreamCode = Number(error.upstreamCode);
    const mcpCode = mapUpstreamCode(upstreamCode);
    return {
      code: mcpCode,
      message: buildUserMessage(mcpCode, error.message),
      upstreamCode,
      httpStatus: typeof error.httpStatus === "number" ? error.httpStatus : undefined,
    };
  }
  // ...
}

Sources: src/common/errors.ts:60-75

Error Response Format

All errors are returned in a standardized format:

ERROR[ERROR_CODE] (upstream=XXX): Human-readable message

Example error responses:

ScenarioResponse Format
Invalid tokenERROR[INVALID_TOKEN] (upstream=N/A): Token is invalid or inactive. Update your JUSTONEAPI_TOKEN
Rate limitedERROR[RATE_LIMITED] (upstream=302): Rate limit exceeded. Please slow down and retry later.
Network timeoutERROR[NETWORK_TIMEOUT] (upstream=N/A): Request timed out. Check network or retry.

Security Considerations

Token Masking in Logs

Debug logging masks tokens to prevent accidental exposure.

// src/common/config.ts:50-65
export function toSafeUrlForLog(fullUrl: string): string {
  try {
    const u = new URL(fullUrl);
    if (u.searchParams.has("token")) {
      u.searchParams.set("token", maskToken(u.searchParams.get("token") ?? ""));
    }
    return u.toString();
  } catch {
    // Fallback: best-effort masking
    return fullUrl.replace(/token=([^&]+)/g, (_m, g1) => `token=${maskToken(g1)}`);
  }
}

Sources: src/common/config.ts:50-65

Retry Behavior with Tokens

Retry logic applies only to transient failures, not authentication errors:

// src/common/http.ts:70-80
const retryable =
  error.name === "AbortError" ||
  (typeof httpStatus === "number" && httpStatus >= 500) ||
  error.code === "ECONNRESET" ||
  error.code === "ECONNREFUSED" ||
  error.code === "ENOTFOUND";
RetryableNot Retryable
Timeout (AbortError)HTTP 4xx errors
HTTP 5xx errorsBusiness code != 0
Network resetInvalid token

Configuration Examples

Claude Desktop Configuration

{
  "mcpServers": {
    "justoneapi": {
      "command": "npx",
      "args": ["-y", "justoneapi-mcp"],
      "env": {
        "JUSTONEAPI_TOKEN": "your_actual_token_here"
      }
    }
  }
}

Custom Timeout and Debug Settings

{
  "mcpServers": {
    "justoneapi": {
      "command": "npx",
      "args": ["-y", "justoneapi-mcp"],
      "env": {
        "JUSTONEAPI_TOKEN": "your_actual_token_here",
        "JUSTONEAPI_TIMEOUT_MS": "30000",
        "JUSTONEAPI_DEBUG": "true"
      }
    }
  }
}

When debug mode is enabled, logs appear with masked tokens:

[justoneapi] GET https://api.justoneapi.com/api/search/v1?token=sk_***&keyword=AI (attempt 1/2)

Obtaining a Token

  1. Visit https://justoneapi.com
  2. Create an account or sign in at https://dashboard.justoneapi.com
  3. Generate an API token from your dashboard
  4. Configure the token in your MCP host
  • README.md — Installation and quick start guide
  • TOOLS.md — Complete tool reference with authentication parameters

Sources: src/index.ts:45-52

System Architecture

Related topics: HTTP Client Implementation, Unified Search Tool, Kuaishou Video Search Tool

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Component Overview

Continue reading this section for the full explanation and source context.

Section Module Dependency Graph

Continue reading this section for the full explanation and source context.

Section Request Flow

Continue reading this section for the full explanation and source context.

Related topics: HTTP Client Implementation, Unified Search Tool, Kuaishou Video Search Tool

System Architecture

Overview

The justoneapi-mcp is a Model Context Protocol (MCP) server that provides a bridge between AI assistants and the JustOneAPI social media search platform. The system enables natural language querying across multiple Chinese social media platforms including Weibo, WeChat, Zhihu, Douyin, Xiaohongshu, Bilibili, Kuaishou, and news sources.

The architecture follows a transport-oriented design philosophy, prioritizing stability, transparency, and raw data fidelity over convenience. The MCP server returns unmodified upstream API responses to ensure maximum data fidelity and long-term compatibility.

High-Level Architecture

graph TD
    subgraph "MCP Host Environment"
        A[MCP Client<br/>Claude Desktop/Cursor]
    end
    
    subgraph "justoneapi-mcp Server"
        B[MCP SDK Server]
        C[Tool Handlers]
        D[Common Libraries]
        E[HTTP Client]
    end
    
    subgraph "External Services"
        F[JustOneAPI<br/>api.justoneapi.com]
        G[Chinese Social Media<br/>Platforms]
    end
    
    A -->|MCP Protocol| B
    B --> C
    C --> D
    D --> E
    E -->|HTTPS| F
    F -->|API Responses| G
    
    style A fill:#e1f5fe
    style F fill:#fff3e0
    style G fill:#f3e5f5

Core Components

Component Overview

ComponentFile LocationPurpose
MCP Serversrc/index.tsEntry point, tool registration, request routing
Tool Handlerssrc/tools/*Individual tool implementations
HTTP Clientsrc/common/http.tsHTTP request management with retry logic
Configurationsrc/common/config.tsToken management, URL sanitization
Error Handlingsrc/common/errors.tsError code mapping and payload transformation

Module Dependency Graph

graph LR
    subgraph "Entry Point"
        A[src/index.ts]
    end
    
    subgraph "Tool Layer"
        B[unified_search_v1.ts]
        C[kuaishou_search_video_v2.ts]
    end
    
    subgraph "Common Layer"
        D[config.ts]
        E[http.ts]
        F[errors.ts]
    end
    
    subgraph "External"
        G[JustOneAPI]
    end
    
    A --> B
    A --> C
    B --> D
    B --> E
    B --> F
    C --> D
    C --> E
    C --> F
    E --> F
    E --> G
    
    style A fill:#ffecb3
    style D fill:#c8e6c9
    style E fill:#c8e6c9
    style F fill:#c8e6c9
    style G fill:#fff3e0

Tool Registration System

Request Flow

sequenceDiagram
    participant Client as MCP Client
    participant Server as MCP Server
    participant Handler as Tool Handler
    participant HTTP as HTTP Client
    participant API as JustOneAPI
    
    Client->>Server: Tool Request (unified_search_v1)
    Server->>Handler: Forward Input
    Handler->>Handler: Validate with Zod Schema
    Handler->>HTTP: GET /api/search/v1
    HTTP->>HTTP: Token encoding
    HTTP->>API: Request with token
    API-->>HTTP: JSON Response
    HTTP-->>Handler: Raw JSON
    Handler-->>Server: JSON Response
    Server-->>Client: MCP Response

Tool Registration Pattern

Tools are registered in src/index.ts using the MCP SDK's registerTool method. Each tool registration includes:

  1. Tool name - Unique identifier following {platform}_{action}_{version} pattern
  2. Input schema - Zod schema for parameter validation
  3. Handler function - Async function that processes requests
// Registration pattern from src/index.ts:55-72
server.registerTool(
  "unified_search_v1",
  {
    description: "Unified search across multiple platforms...",
    inputSchema: UnifiedSearchV1Input.shape,
  },
  async (input) => {
    try {
      const data = await unifiedSearchV1(input);
      return {
        content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
      };
    } catch (e: unknown) {
      const m = toMcpErrorPayload(e);
      return {
        isError: true,
        content: [{ type: "text", text: `ERROR[${m.code}]: ${m.message}` }],
      };
    }
  }
);

HTTP Client Architecture

Retry Strategy

The HTTP client in src/common/http.ts implements an intelligent retry mechanism with exponential backoff.

graph TD
    A[Request] --> B{Attempt < Max?}
    B -->|Yes| C{Check Retryable?}
    C -->|AbortError| D[Retry]
    C -->|HTTP 5xx| D
    C -->|ECONNRESET| D
    C -->|ECONNREFUSED| D
    C -->|ENOTFOUND| D
    C -->|No| E[Throw Error]
    D --> F[Wait 250ms × Attempt]
    F --> G[Retry Request]
    G --> B
    B -->|No| H[Throw Last Error]
    
    style E fill:#ffcdd2
    style H fill:#ffcdd2
    style D fill:#c8e6c9

Retryable Conditions

ConditionTypeRetry Behavior
AbortErrorTimeout✅ Retry
HTTP 5xxServer Error✅ Retry
ECONNRESETConnection Reset✅ Retry
ECONNREFUSEDConnection Refused✅ Retry
ENOTFOUNDDNS Lookup Failed✅ Retry
HTTP 4xxClient Error❌ No Retry
Business ErrorsAPI Code❌ No Retry

Sources: src/common/http.ts:29-36

Error Handling System

Error Flow

graph TD
    A[Exception Thrown] --> B{Error Type?}
    B -->|AbortError| C[NETWORK_TIMEOUT]
    B -->|upstreamCode exists| D[Map Upstream Code]
    B -->|httpStatus exists| E[UPSTREAM_ERROR]
    B -->|cause or network code| F[NETWORK_ERROR]
    B -->|Unknown| G[UPSTREAM_ERROR]
    
    D --> H[Return MCP Error Payload]
    C --> H
    E --> H
    F --> H
    G --> H
    
    style C fill:#fff9c4
    style D fill:#fff9c4
    style E fill:#fff9c4
    style F fill:#fff9c4

Error Code Mapping

MCP Error CodeUpstream CodeDescriptionUser Action
INVALID_TOKENN/AToken invalid/inactiveUpdate JUSTONEAPI_TOKEN
COLLECT_FAILEDN/AData collection failedRetry after delay
RATE_LIMITED302Too many requestsSlow down, retry later
DAILY_QUOTA_EXCEEDEDN/ADaily limit reachedWait until tomorrow
INSUFFICIENT_BALANCEN/ALow account balanceTop up account
PERMISSION_DENIEDN/ANo access to resourceContact support
VALIDATION_ERRORN/AInvalid parametersCheck input values
INTERNAL_ERRORN/AServer errorRetry later
NETWORK_TIMEOUTN/ARequest timed outCheck network
NETWORK_ERRORN/AConnection failedCheck internet
UPSTREAM_ERRORN/AUnspecified upstreamRetry or contact support

Configuration Management

Environment Variables

VariableRequiredDefaultDescription
JUSTONEAPI_TOKEN✅ Yes-API authentication token
JUSTONEAPI_BASE_URLNohttps://api.justoneapi.comAPI endpoint base URL
JUSTONEAPI_TIMEOUT_MSNo20000Request timeout in milliseconds
JUSTONEAPI_RETRYNo1Number of retries after first attempt
JUSTONEAPI_DEBUGNofalseEnable debug logging to stderr

Token Management

The requireToken() function in src/common/config.ts validates and retrieves the API token:

export function requireToken(): string {
  const token = process.env.JUSTONEAPI_TOKEN?.trim();
  if (!token) {
    throw new Error("JUSTONEAPI_TOKEN environment variable is required");
  }
  return token;
}

URL Sanitization for Logging

The toSafeUrlForLog() function masks sensitive tokens in URLs before logging:

graph LR
    A[Full URL with token] --> B[Parse URL]
    B --> C{Token param exists?}
    C -->|Yes| D[Mask token value]
    C -->|No| E[Return original]
    D --> F[Return sanitized URL]
    E --> F

Tool Specifications

Available Tools

Tool NamePurposeVersion
unified_search_v1Multi-platform social media searchv1
kuaishou_search_video_v2Kuaishou-specific video searchv2

Platform Support

The unified search supports the following platforms:

PlatformIdentifierType
All PlatformsALLDefault
NewsNEWSNews content
WeiboWEIBOSocial posts
WeChatWEIXINArticles
ZhihuZHIHUQ&A content
DouyinDOUYINShort videos
XiaohongshuXIAOHONGSHULifestyle content
BilibiliBILIBILILong-form videos
KuaishouKUAISHOUShort videos

Search Syntax Support

OperatorSyntaxDescription
Single keyworddeepseekBasic search
AND searchdeepseek chatgptBoth keywords required
OR searchdeepseek~chatgptEither keyword matches
NOT searchdeepseek -chatgptExclude keyword

Data Flow Architecture

Unified Search Flow

sequenceDiagram
    participant User
    participant Handler as unified_search_v1
    participant HTTP as getJson
    participant API as JustOneAPI
    
    User->>Handler: {keyword, source, start, end}
    Handler->>Handler: Encode parameters
    Handler->>HTTP: GET /api/search/v1?token=...&keyword=...
    HTTP->>API: HTTPS Request
    API-->>HTTP: {code, message, data, nextCursor}
    HTTP-->>Handler: Raw JSON response
    Handler-->>User: JSON with raw data
    
    Note over User,API: Raw upstream data returned unchanged

Technology Stack

Production Dependencies

PackageVersionPurpose
@modelcontextprotocol/sdk^1.25.1MCP protocol implementation
zod^4.3.4Schema validation
dotenv^17.2.3Environment variable loading

Development Dependencies

PackageVersionPurpose
typescript^5.9.3Type safety
eslint^9.39.2Code linting
prettier^3.7.4Code formatting
ts-node^10.9.2TypeScript execution

Node.js Requirement

  • Minimum version: Node.js 18.0.0
  • Runtime: ES2022+ module system

Startup and Initialization

Configuration Validation

On server startup, the main function validates that required configuration exists:

graph TD
    A[Server Start] --> B{JUSTONEAPI_TOKEN set?}
    B -->|No| C[Exit with Error]
    B -->|Yes| D[Start MCP Server]
    D --> E[Register Tools]
    E --> F[Listen for Requests]
    
    style C fill:#ffcdd2
    style F fill:#c8e6c9

The token validation occurs in src/index.ts before the MCP server begins accepting connections, ensuring early failure with clear error messages.

Design Philosophy

The architecture embodies the "Transport, not transformation" principle:

  1. Maximum Data Fidelity - Raw upstream responses are returned unmodified
  2. No Field Parsing - Data structures remain as received from upstream APIs
  3. No Data Restructuring - No normalization or transformation of response formats
  4. Long-term Compatibility - Stable interface despite upstream API changes

Sources: src/common/http.ts:29-36

HTTP Client Implementation

Related topics: System Architecture, Error Handling, Configuration Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Request Flow

Continue reading this section for the full explanation and source context.

Section ApiError Type

Continue reading this section for the full explanation and source context.

Section getJson Function

Continue reading this section for the full explanation and source context.

Related topics: System Architecture, Error Handling, Configuration Reference

HTTP Client Implementation

Overview

The HTTP Client Implementation provides a centralized, reusable HTTP communication layer for the JustOneAPI MCP server. It handles all outbound API requests with built-in retry logic, timeout management, error normalization, and secure logging. The implementation follows a "transport, not transformation" philosophy, returning raw upstream responses to maintain maximum data fidelity.

Key Responsibilities:

  • Execute HTTP GET requests to the JustOneAPI backend
  • Manage request timeouts using AbortController
  • Implement automatic retry with exponential backoff for transient failures
  • Normalize errors into structured MCP error codes
  • Ensure secure logging by masking sensitive tokens

Sources: src/common/http.ts:48-68

Architecture

graph TD
    A[Tool Handler] --> B[API Function<br/>e.g., unifiedSearchV1]
    B --> C[getJson]
    C --> D{Token Validation}
    D -->|Invalid| E[INVALID_TOKEN Error]
    D -->|Valid| F[Build URL]
    F --> G[Fetch with Timeout]
    G --> H{Response OK?}
    H -->|No| I[Retry Logic]
    I --> G
    H -->|Yes| J[Parse JSON]
    J --> K[Business Code OK?]
    K -->|No| L[Error Mapping]
    K -->|Yes| M[Return Response]
    L --> N[MCP Error Payload]
    
    style E fill:#ff6b6b
    style N fill:#ffa500
    style M fill:#51cf66

Request Flow

  1. Token Validation - Ensures JUSTONEAPI_TOKEN exists before making requests Sources: src/common/http.ts:60 src/common/config.ts
  1. URL Construction - Builds full URL with base URL and query parameters Sources: src/common/http.ts:62
  1. Fetch Execution - Makes HTTP request with AbortController timeout Sources: src/common/http.ts:70-76
  1. Response Processing - Validates HTTP status and parses JSON Sources: src/common/http.ts:78-88
  1. Business Logic Check - Validates upstream code === 0 for success Sources: src/common/errors.ts:1-18

Core Components

ApiError Type

The ApiError interface extends the standard Error type with additional properties for HTTP-level and business-level error information.

PropertyTypeDescription
httpStatus`number \undefined`HTTP status code from the fetch response
upstreamCode`number \undefined`Business error code from upstream API response
payload`unknown \undefined`Full response payload when available
code`string \undefined`Node.js error code for network errors
cause`unknown \undefined`Underlying error cause

Sources: src/common/http.ts:39-45

getJson Function

The main HTTP client function that performs GET requests with comprehensive error handling.

export async function getJson(pathWithQuery: string): Promise<UpstreamResponse>

Parameters:

ParameterTypeDescription
pathWithQuerystringAPI endpoint path including query string

Returns: Promise<UpstreamResponse> - Parsed JSON response from the API

Behavior:

  • Validates token presence before any network call
  • Supports configurable retry attempts (default: 1 retry after initial attempt)
  • Implements 250ms backoff between retries
  • Returns raw upstream JSON without transformation

Sources: src/common/http.ts:48-68

Retry Logic

The HTTP client implements intelligent retry behavior for transient failures.

Retry Conditions

ConditionRetryableDescription
AbortErrorYesRequest timeout
HTTP 5xxYesServer-side errors
ECONNRESETYesConnection reset by peer
ECONNREFUSEDYesConnection refused
ENOTFOUNDYesDNS lookup failure
HTTP 4xxNoClient errors
Business code != 0NoApplication-level errors
graph LR
    A[Request Attempt] --> B{Error Type?}
    B -->|AbortError| C[Retry]
    B -->|5xx| C
    B -->|Network Error| C
    B -->|4xx| D[No Retry]
    B -->|Business Error| D
    C --> E{Attempts<br/>Exhausted?}
    E -->|No| A
    E -->|Yes| F[Throw Error]
    D --> F

Retry Configuration:

  • Maximum attempts: 1 + JUSTONEAPI_RETRY (default: 2 total attempts)
  • Backoff delay: 250ms * attempt_number

Sources: src/common/http.ts:68-96

Timeout Management

Timeouts are implemented using the AbortController API for native browser/Node.js compatibility.

SettingEnvironment VariableDefaultDescription
Request TimeoutJUSTONEAPI_TIMEOUT_MS20000Timeout in milliseconds

Implementation:

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), config.timeoutMs);

const res = await fetch(url, { method: "GET", signal: controller.signal });
// ... process response ...
clearTimeout(timer); // Clean up timer

When a timeout occurs, an AbortError is thrown, which triggers the retry logic.

Sources: src/common/http.ts:70-76

Error Handling

Error Code Mapping

The system maps upstream error codes to standardized MCP error codes.

Upstream CodeMCP CodeDescription
301INVALID_TOKENToken is invalid or inactive
302INVALID_TOKENToken validation failed
401INVALID_TOKENAuthentication required
402INSUFFICIENT_BALANCEAccount balance too low
403PERMISSION_DENIEDNo access to resource
404PERMISSION_DENIEDResource not found
422VALIDATION_ERRORInvalid request parameters
429RATE_LIMITEDToo many requests
500INTERNAL_ERRORServer error
503UPSTREAM_ERRORService unavailable

Sources: src/common/errors.ts:19-53

Error Payload Structure

When an error occurs, the toMcpErrorPayload function converts the error to a structured format.

{
  code: JOAErrorCode;      // Normalized MCP error code
  message: string;         // Human-readable message
  upstreamCode?: number;  // Original upstream error code
  httpStatus?: number;     // HTTP status code
}

Error Priority:

  1. AbortErrorNETWORK_TIMEOUT
  2. upstreamCode present → Maps to appropriate MCP code
  3. httpStatus present → UPSTREAM_ERROR
  4. cause or network error code → NETWORK_ERROR
  5. Fallback → UPSTREAM_ERROR

Sources: src/common/errors.ts:55-91

Security Features

Token Masking

All API tokens are masked in logs to prevent credential leakage.

export function toSafeUrlForLog(fullUrl: string): string {
  try {
    const u = new URL(fullUrl);
    if (u.searchParams.has("token")) {
      u.searchParams.set("token", maskToken(u.searchParams.get("token") ?? ""));
    }
    return u.toString();
  } catch {
    // Fallback: best-effort masking
    return fullUrl.replace(/token=([^&]+)/g, (_m, g1) => `token=${maskToken(g1)}`);
  }
}

Features:

  • Primary method uses URL API for accurate parsing
  • Fallback regex for non-standard URLs
  • Two-level fallback to prevent logging failures

Sources: src/common/config.ts:58-74

Debug Logging

When JUSTONEAPI_DEBUG=true, requests are logged to stderr with masked tokens:

[justoneapi] GET https://api.justoneapi.com/api/search/v1?token=***&keyword=AI (attempt 1/2)

Sources: src/common/http.ts:72-74

Configuration

Environment Variables

VariableRequiredDefaultDescription
JUSTONEAPI_TOKENYes-API authentication token
JUSTONEAPI_BASE_URLNohttps://api.justoneapi.comAPI endpoint base URL
JUSTONEAPI_TIMEOUT_MSNo20000Request timeout in milliseconds
JUSTONEAPI_RETRYNo1Number of retries after initial attempt
JUSTONEAPI_DEBUGNofalseEnable debug logging

Sources: README.md:103-110

Usage Examples

Basic Tool Implementation

Tools in this MCP server use the HTTP client through dedicated API functions:

// From unified_search_v1.ts
export async function unifiedSearchV1(input: z.infer<typeof UnifiedSearchV1Input>) {
  const token = encodeURIComponent(requireToken());
  const keyword = encodeURIComponent(input.keyword);

  const params = new URLSearchParams();
  params.append("token", token);
  params.append("keyword", keyword);

  if (input.source) {
    params.append("source", input.source);
  }

  if (input.nextCursor) {
    params.append("nextCursor", input.nextCursor);
  } else {
    params.append("start", input.start);
    params.append("end", input.end);
  }

  return await getJson(`/api/search/v1?${params.toString()}`);
}

Sources: src/tools/search/unified_search_v1.ts:29-54

Error Response Format

All errors are returned in a consistent MCP format:

ERROR[ERROR_CODE] (upstream=XXX): Human-readable message

Example:

ERROR[RATE_LIMITED] (upstream=302): Rate limit exceeded. Please slow down and retry later.

Sources: README.md:86-89

Integration with MCP Server

The HTTP client is integrated into the MCP server's tool registration system:

server.registerTool(
  "unified_search_v1",
  {
    description: "Unified search across multiple platforms...",
    inputSchema: UnifiedSearchV1Input.shape,
  },
  async (input) => {
    try {
      const data = await unifiedSearchV1(input);
      return {
        content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
      };
    } catch (e: unknown) {
      const m = toMcpErrorPayload(e);
      return {
        isError: true,
        content: [
          {
            type: "text",
            text: `ERROR[${m.code}] (upstream=${m.upstreamCode ?? "N/A"}): ${m.message}`,
          },
        ],
      };
    }
  }
);

Sources: src/index.ts:50-70

Dependencies

The HTTP client implementation uses the following dependencies:

PackageVersionPurpose
@modelcontextprotocol/sdk^1.25.1MCP server framework
zod^4.3.4Schema validation
dotenv^17.2.3Environment variable loading

Sources: package.json:16-23

Sources: src/common/http.ts:48-68

Unified Search Tool

Related topics: Kuaishou Video Search Tool, Tool Naming Conventions and Standards, Error Handling

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Context

Continue reading this section for the full explanation and source context.

Section Request Flow

Continue reading this section for the full explanation and source context.

Section Cursor-Based Pagination

Continue reading this section for the full explanation and source context.

Related topics: Kuaishou Video Search Tool, Tool Naming Conventions and Standards, Error Handling

Unified Search Tool

Overview

The Unified Search Tool (unified_search_v1) is the primary MCP (Model Context Protocol) tool provided by justoneapi-mcp. It enables aggregated searching across multiple Chinese social media platforms and news sources through a single API interface.

Key Characteristics:

  • Searches 8 platforms simultaneously in one request
  • Returns raw, unmodified JSON from upstream APIs
  • Supports advanced search syntax (AND, OR, NOT operators)
  • Implements cursor-based pagination
  • UTC+8 timezone for all date/time operations

Sources: TOOLS.md:43-60

Architecture

System Context

graph TD
    subgraph "MCP Host"
        A[Claude / Cursor]
    end
    
    subgraph "justoneapi-mcp"
        B[Server Entry<br/>src/index.ts]
        C[Tool Handler<br/>unified_search_v1]
        D[HTTP Client<br/>src/common/http.ts]
        E[Error Handler<br/>src/common/errors.ts]
    end
    
    subgraph "External"
        F[JustOneAPI<br/>api.justoneapi.com]
    end
    
    A -->|MCP Protocol| B
    B --> C
    C --> D
    D -->|GET /api/search/v1| F
    F -->|JSON Response| D
    D --> E
    
    style F fill:#f9f,stroke:#333
    style D fill:#bbf,stroke:#333
    style E fill:#fbb,stroke:#333

Request Flow

sequenceDiagram
    participant MCP as MCP Host
    participant Server as justoneapi-mcp
    participant HTTP as HTTP Client
    participant API as JustOneAPI
    
    MCP->>Server: unified_search_v1(params)
    Server->>HTTP: getJson(endpoint, params)
    
    loop Retry Logic (max 2 attempts)
        HTTP->>API: GET /api/search/v1
        API-->>HTTP: JSON Response
        
        alt Success (code=0)
            HTTP-->>Server: data
        else Retryable Error (5xx, timeout)
            HTTP->>HTTP: Wait 250ms * attempt
        end
    end
    
    alt Non-retryable Error
        Server->>Server: toMcpErrorPayload(e)
        Server-->>MCP: ERROR[...]
    else Success
        Server-->>MCP: Raw JSON response
    end

Sources: src/index.ts:29-47 Sources: src/common/http.ts:1-44

Parameters

ParameterTypeRequiredDescription
keywordstringYesSearch keyword with advanced syntax support
sourcestringNoPlatform filter (default: ALL)
startstringConditionalStart time yyyy-MM-dd HH:mm:ss (UTC+8)
endstringConditionalEnd time yyyy-MM-dd HH:mm:ss (UTC+8)
nextCursorstringNoPagination cursor from previous response

Note: start and end are required for the first page request. They must be omitted when using nextCursor for pagination.

Sources: src/tools/search/unified_search_v1.ts:16-41

Supported Platforms

Platform IDDescription
ALLSearch all platforms (default)
NEWSNews articles
WEIBOSina Weibo
WEIXINWeChat public accounts
ZHIHUZhihu Q&A
DOUYINDouyin (TikTok China)
XIAOHONGSHUXiaohongshu (Little Red Book)
BILIBILIBilibili video platform
KUAISHOUKuaishou short video

Sources: src/tools/search/unified_search_v1.ts:9-16

Search Syntax

The unified search supports advanced query operators:

OperatorSyntaxExampleDescription
Single keywordworddeepseekSearch for exact term
AND (implicit)word1 word2deepseek chatgptBoth terms must appear
ORword1~word2deepseek~chatgptEither term may appear
NOTword -excludedeepseek -chatgptExclude term from results

Syntax Rules:

  • Single keyword: Plain text match
  • AND operator: Space-separated terms (implicit)
  • OR operator: Tilde (~) separator
  • NOT operator: Dash (-) prefix on exclusion term

Sources: TOOLS.md:62-69

Pagination

Cursor-Based Pagination

graph LR
    A[First Request<br/>start, end] --> B[Response<br/>data + nextCursor]
    B --> C{Next Page?}
    C -->|Yes| D[Next Request<br/>nextCursor]
    D --> E[Response<br/>data + nextCursor]
    E --> C
    C -->|No| F[Done]

Pagination Rules

  1. First Request: Include start and end time parameters
  2. Subsequent Requests: Use nextCursor instead of time parameters
  3. Final Page: Response without nextCursor indicates completion

When nextCursor is provided, start, end, and source parameters should be omitted—the cursor contains all necessary pagination context.

Sources: TOOLS.md:32-42

Response Format

Success Response

{
  "code": 0,
  "message": null,
  "recordTime": "2025-01-02T14:55:21Z",
  "data": {
    // Platform-specific data structure
  }
}

Error Response

ERROR[ERROR_CODE] (upstream=XXX): Human-readable message
Error CodeDescriptionRecovery Action
INVALID_TOKENToken invalid or inactiveUpdate JUSTONEAPI_TOKEN
RATE_LIMITEDToo many requestsSlow down and retry
DAILY_QUOTA_EXCEEDEDDaily limit reachedWait or upgrade plan
INSUFFICIENT_BALANCELow account balanceTop up account
VALIDATION_ERRORInvalid parametersCheck input values
NETWORK_TIMEOUTRequest timed outCheck network/retry
NETWORK_ERRORConnection failedCheck internet
UPSTREAM_ERRORServer errorRetry or contact support

Sources: src/common/errors.ts:1-72

Configuration

Environment Variables

VariableRequiredDefaultDescription
JUSTONEAPI_TOKENYesAPI authentication token
JUSTONEAPI_BASE_URLNohttps://api.justoneapi.comAPI endpoint
JUSTONEAPI_TIMEOUT_MSNo20000Request timeout (ms)
JUSTONEAPI_RETRYNo1Retry attempts
JUSTONEAPI_DEBUGNofalseDebug logging

MCP Server Configuration

{
  "mcpServers": {
    "justoneapi": {
      "command": "npx",
      "args": ["-y", "justoneapi-mcp"],
      "env": {
        "JUSTONEAPI_TOKEN": "your_token_here"
      }
    }
  }
}

Usage Examples

Search for "AI" discussions on all platforms from January 1-5, 2025

Generated Parameters:

{
  "keyword": "AI",
  "source": "ALL",
  "start": "2025-01-01 00:00:00",
  "end": "2025-01-05 23:59:59"
}
Search for "chatgpt" on Weibo only, from December 1st to January 2nd

Generated Parameters:

{
  "keyword": "chatgpt",
  "source": "WEIBO",
  "start": "2024-12-01 00:00:00",
  "end": "2025-01-02 23:59:59"
}

Complex Query with OR and NOT

Search for posts containing "deepseek" OR "机器学习" but NOT "广告"

Generated Parameters:

{
  "keyword": "deepseek~机器学习 -广告",
  "source": "ZHIHU",
  "start": "2025-01-01 00:00:00",
  "end": "2025-01-31 23:59:59"
}

Pagination Request

When continuing from a previous response:

{
  "keyword": "AI",
  "nextCursor": "eyJsYXN0SWQiOiIxMjM0NTY3ODkwIn0="
}

Sources: README.md:1-80

Design Philosophy

The Unified Search Tool follows the "Transport, not transformation" principle:

  • Maximum data fidelity: Returns unmodified upstream JSON responses
  • No field parsing: Raw response structure preserved
  • No data restructuring: Original field names and hierarchy maintained
  • Long-term compatibility: Interface stability prioritized over convenience

This approach ensures that clients receive complete, unmodified data for any downstream processing needs.

Sources: README.md:95-105

Implementation

Error with Openai API: output new_sensitive (1027)

Please check that you have set the OPENAI_API_KEY environment variable with a valid API key.

Sources: TOOLS.md:43-60

Tool Naming Conventions and Standards

Related topics: Unified Search Tool, Kuaishou Video Search Tool

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Component Breakdown

Continue reading this section for the full explanation and source context.

Section Syntax Rules

Continue reading this section for the full explanation and source context.

Section Reserved Platform Identifiers

Continue reading this section for the full explanation and source context.

Related topics: Unified Search Tool, Kuaishou Video Search Tool

Tool Naming Conventions and Standards

Overview

The justoneapi-mcp project implements a standardized naming convention for all MCP (Model Context Protocol) tools. This convention ensures consistency, predictability, and scalability across the entire tool ecosystem. The naming standard follows a three-part pattern that clearly communicates the tool's scope, purpose, and version in a single identifier.

The primary objectives of this naming standard include:

  • Discoverability: Tools can be easily identified and located based on their naming pattern
  • Versioning: API evolution is managed through version suffixes
  • Consistency: All contributors follow the same pattern, reducing cognitive load
  • Scalability: New tools can be added following the established convention without ambiguity

Sources: README.md:73

Naming Pattern Structure

All tools in the justoneapi-mcp server follow a unified naming pattern:

{platform}_{action}_{version}

This three-component structure provides immediate context about each tool's purpose and scope.

Component Breakdown

ComponentPurposeExamplesDescription
platformIdentifies the target servicekuaishou, unifiedThe platform or scope the tool operates on
actionDescribes the operationsearch, search_videoWhat the tool does, can be compound with underscore
versionIndicates API versionv1, v2Version of the underlying API endpoint

Syntax Rules

  1. Delimiter: Components are separated by underscores (_), not camelCase or hyphens
  2. Lowercase: All components use lowercase letters exclusively
  3. Compound actions: Multi-word actions use underscores (e.g., search_video)
  4. Version format: Version uses lowercase v followed by a number (e.g., v1, v2)

Sources: README.md:74-76

Current Tool Registry

The following table lists all currently available tools in the justoneapi-mcp server:

Tool NamePlatformActionVersionPurpose
unified_search_v1unifiedsearchv1Multi-platform search across Weibo, WeChat, Zhihu, Douyin, Xiaohongshu, Bilibili, Kuaishou, and News
kuaishou_search_video_v2kuaishousearch_videov2Platform-specific video search for Kuaishou

Sources: src/index.ts:24-46

Platform Component Standards

Reserved Platform Identifiers

The platform component identifies the target service or search domain:

PlatformDescriptionSupported Actions
unifiedAggregated multi-platform searchsearch
kuaishouKuaishou video platformsearch_video
weiboWeibo social platform (planned)search
zhihuZhihu Q&A platform (planned)search
douyinDouyin short video (planned)search_video
bilibiliBilibili video platform (planned)search_video

Sources: TOOLS.md:34-40

Naming Future Platforms

When adding new platforms, follow these guidelines:

  1. Use the lowercase English name of the platform
  2. If the platform name contains multiple words, use the most common short form
  3. Avoid abbreviations unless they are universally recognized
  4. Ensure uniqueness across all existing platform names

Action Component Standards

Single-Word Actions

Simple actions use a single lowercase word:

  • search - General search functionality
  • analyze - Data analysis operations
  • fetch - Data retrieval operations

Compound Actions

Actions with multiple components use underscores to separate words:

ActionComponentsMeaning
search_videosearch + videoVideo search functionality
search_usersearch + userUser profile search
fetch_trendingfetch + trendingTrending content retrieval

Sources: src/tools/kuaishou/search_video_v2.ts:1-15

Version Component Standards

Versioning Strategy

The version component follows semantic versioning principles adapted for API evolution:

Version PatternMeaningUpgrade Consideration
v1Initial stable releaseBreaking changes unlikely
v2Major version with potential breaking changesCheck changelog before upgrading
v{n}Future major versionsEach increment may introduce breaking changes

Version Upgrade Triggers

Consider incrementing the version when:

  • Breaking API changes: Parameter types, required fields, or return structure change
  • Behavior changes: Same inputs produce different outputs
  • Deprecations: Removing functionality from a tool
  • Major architectural changes: Internal refactoring affecting external behavior

Version Coexistence

Multiple versions of the same tool may coexist, allowing gradual migration:

  • Old versions remain available for backward compatibility
  • New versions receive new features and improvements
  • Deprecation notices appear in documentation

Implementation Architecture

Tool Registration Flow

The following diagram illustrates how tools are registered and exposed through the MCP server:

graph TD
    A[Tool Definition File] --> B[Zod Input Schema]
    A --> C[Tool Handler Function]
    B --> D[registerTool in index.ts]
    C --> D
    D --> E[McpServer Instance]
    E --> F[STDIO Transport]
    F --> G[MCP Host Client]
    
    H[Tool Name: kuaishou_search_video_v2] --> D
    I[Tool Name: unified_search_v1] --> D

Tool Registration Code Structure

Tools are registered in src/index.ts using the MCP SDK's registerTool method:

server.registerTool(
  "kuaishou_search_video_v2",
  {
    description: "Search Kuaishou videos by keyword...",
    inputSchema: KuaishouSearchVideoV2Input.shape,
  },
  async (input) => {
    try {
      const data = await kuaishouSearchVideoV2(input);
      return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
    } catch (e: unknown) {
      const m = toMcpErrorPayload(e);
      return { isError: true, content: [...] };
    }
  }
);

Sources: src/index.ts:24-46

Input Schema Conventions

Zod-Based Validation

All tools use Zod schemas for input validation, ensuring type safety and automatic documentation:

export const KuaishouSearchVideoV2Input = z.object({
  keyword: z.string().min(1).describe("Search keyword, e.g. 'dance'"),
  page: z.number().int().min(1).default(1).describe("Page number, default 1"),
});

Schema Documentation Pattern

Each parameter includes:

FieldPurposeMethods
describe()Human-readable descriptionRequired for all parameters
.min()Minimum value constraintFor strings and numbers
.default()Default value if omittedOptional parameters
.optional()Marks non-required parametersOptional parameters

Sources: src/tools/kuaishou/search_video_v2.ts:4-9

Unified Search Tool Specification

`unified_search_v1`

The unified search tool provides cross-platform search capabilities with advanced syntax support.

#### Parameters

ParameterTypeRequiredDescription
keywordstringYesSearch keyword with syntax: single word, AND word1 word2, OR word1~word2, NOT word -excluded
sourceenumNoPlatform filter: ALL, NEWS, WEIBO, WEIXIN, ZHIHU, DOUYIN, XIAOHONGSHU, BILIBILI, KUAISHOU
startstringConditionalStart time yyyy-MM-dd HH:mm:ss (UTC+8). Required for first page
endstringConditionalEnd time yyyy-MM-dd HH:mm:ss (UTC+8). Required for first page
nextCursorstringNoPagination cursor from previous response

#### Search Syntax Examples

SyntaxExampleMeaning
Single keyworddeepseekPosts containing "deepseek"
AND searchdeepseek chatgptPosts containing both terms
OR searchdeepseek~chatgptPosts containing either term
NOT searchdeepseek -chatgptPosts with "deepseek" but not "chatgpt"

Sources: src/tools/search/unified_search_v1.ts:1-42

Platform-Specific Tool Specification

`kuaishou_search_video_v2`

The Kuaishou video search tool provides platform-specific video search functionality.

#### Parameters

ParameterTypeRequiredDefaultDescription
keywordstringYes-Search keyword, minimum 1 character
pagenumberNo1Page number, must be positive integer

#### API Endpoint

GET /api/kuaishou/search-video/v2?token={token}&keyword={keyword}&page={page}

Sources: src/tools/kuaishou/search_video_v2.ts:1-15

Error Handling Integration

Standardized Error Codes

All tools return errors in a consistent format that includes the MCP error code:

ERROR[ERROR_CODE] (upstream=XXX): Human-readable message

Error Code Mapping

MCP CodeTrigger ConditionUpstream CodeUser Action
INVALID_TOKENInvalid or inactive token-Update JUSTONEAPI_TOKEN
RATE_LIMITEDToo many requests302Slow down and retry
DAILY_QUOTA_EXCEEDEDDaily limit reached-Wait until tomorrow
INSUFFICIENT_BALANCELow account balance-Top up account
NETWORK_TIMEOUTRequest timeout-Check network/retry
COLLECT_FAILEDData collection failed-Retry after delay
VALIDATION_ERRORInvalid parameters-Check input values

Sources: src/common/errors.ts:1-60

Error Handler Implementation

export function toMcpErrorPayload(e: unknown): {
  code: JOAErrorCode;
  message: string;
  upstreamCode?: number;
  httpStatus?: number;
} {
  const error = e as {
    name?: string;
    message?: string;
    upstreamCode?: number;
    httpStatus?: number;
  };
  
  if (error.name === "AbortError") {
    return { code: "NETWORK_TIMEOUT", message: buildUserMessage("NETWORK_TIMEOUT") };
  }
  // ... additional error type handling
}

Best Practices

Creating New Tools

Follow these steps to add a new tool:

  1. Choose the name following the {platform}_{action}_{version} pattern
  2. Create the tool file in src/tools/{platform}/
  3. Define the Zod schema with descriptive parameter documentation
  4. Implement the handler using getJson from common/http.ts
  5. Register in index.ts with description and input schema
  6. Add tests for input validation and error handling

File Naming Conventions

Tool TypeLocationFile Name Pattern
Platform-specificsrc/tools/{platform}/{action}_{version}.ts
Unified toolssrc/tools/search/{action}_{version}.ts
Utility functionssrc/common/{purpose}.ts

Documentation Requirements

Each tool must document:

  • All parameters with types and descriptions
  • Required vs optional parameters
  • Default values where applicable
  • Error codes that may be returned
  • Example usage scenarios

Summary

The tool naming convention in justoneapi-mcp provides a clear, consistent, and scalable approach to defining MCP tools. By following the {platform}_{action}_{version} pattern, developers can quickly understand any tool's purpose and scope. The Zod-based schema validation ensures type safety, while standardized error handling provides consistent feedback across all operations.

Key takeaways:

  • Use underscores to separate all components
  • Always include the version suffix (v1, v2, etc.)
  • Use compound action names with underscores when needed
  • Follow the established file structure for organization
  • Leverage Zod schemas for validation and documentation

Sources: README.md:73

Configuration Reference

Related topics: Authentication, HTTP Client Implementation

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Required Variables

Continue reading this section for the full explanation and source context.

Section Optional Variables

Continue reading this section for the full explanation and source context.

Section Module Structure

Continue reading this section for the full explanation and source context.

Related topics: Authentication, HTTP Client Implementation

Configuration Reference

Overview

The justoneapi-mcp server provides a centralized configuration system that manages all runtime settings through environment variables. The configuration module serves as the single source of truth for API credentials, connection parameters, and debugging options.

Configuration is loaded from environment variables at startup and validated before the MCP server begins accepting requests. The system follows a "fail-fast" design pattern, terminating immediately if required parameters are missing.

Sources: src/index.ts:58-64

Environment Variables

Required Variables

VariableTypeRequiredDescription
JUSTONEAPI_TOKENstringYesYour JustOneAPI authentication token. Used for all API requests.

The server validates the token presence on startup. If the token is missing or empty, the server exits with an error message directing users to set the environment variable.

Sources: src/index.ts:58-68

Optional Variables

VariableTypeDefaultDescription
JUSTONEAPI_BASE_URLstringhttps://api.justoneapi.comBase API endpoint for all requests
JUSTONEAPI_TIMEOUT_MSnumber20000Request timeout in milliseconds
JUSTONEAPI_RETRYnumber1Number of retries after initial request failure
JUSTONEAPI_DEBUGbooleanfalseEnable debug logging to stderr

Sources: README.md

Configuration Module Architecture

Module Structure

The configuration system consists of the following exported functions and objects:

// Implemented in src/common/config.ts
export const config: Config;        // Runtime configuration object
export function requireToken(): string;    // Validates and returns token
export function toSafeUrlForLog(url: string): string;  // Sanitizes URLs for logging

Configuration Object

The internal Config interface defines the shape of the runtime configuration:

interface Config {
  token: string;
  baseUrl: string;
  timeoutMs: number;
  retry: number;
  debug: boolean;
}

Token Management

Token Validation

The requireToken() function performs strict validation on the token:

  1. Reads JUSTONEAPI_TOKEN from environment
  2. Trims whitespace from the value
  3. Checks if the token is empty
  4. Returns the validated token string

If validation fails, an error is thrown immediately, preventing server startup.

Sources: src/common/config.ts

Token Usage in HTTP Layer

The token is used in HTTP requests by encoding it for URL safety:

const token = encodeURIComponent(requireToken());

This encoded token is appended to all API requests, including:

  • Unified search: /api/search/v1?token=${token}&keyword=${keyword}
  • Kuaishou video search: /api/kuaishou/search-video/v2?token=${token}&keyword=${keyword}

Sources: src/tools/search/unified_search_v1.ts

HTTP Layer Integration

Request Flow

graph TD
    A[API Tool Called] --> B[getJson Function]
    B --> C[requireToken Validation]
    C --> D[Build URL with Config]
    D --> E[Create AbortController]
    E --> F[Execute Fetch Request]
    F --> G{Success?}
    G -->|Yes| H[Parse JSON Response]
    G -->|No| I{Check Retryable Error}
    I -->|Yes| J[Wait 250ms × Attempt]
    J --> E
    I -->|No| K[Throw Error]
    H --> L[Return UpstreamResponse]
    K --> M[Error Handler]

Configuration Parameters Used

The HTTP module consumes configuration for request handling:

ParameterUsagePurpose
config.baseUrlURL constructionPrepend to all API paths
config.timeoutMsRequest timeoutSet AbortController timer
config.retryRetry logicCalculate total attempt count
config.debugLoggingPrint request details to stderr

Sources: src/common/http.ts

Retry Mechanism

The retry logic uses the JUSTONEAPI_RETRY configuration value:

const attempts = 1 + Math.max(0, Number.isFinite(config.retry) ? config.retry : 0);

Retry occurs only for specific error types:

Error TypeRetryable
AbortError (timeout)✅ Yes
HTTP 5xx status✅ Yes
ECONNRESET✅ Yes
ECONNREFUSED✅ Yes
ENOTFOUND✅ Yes
HTTP 4xx status❌ No
Business code ≠ 0❌ No

Sources: src/common/http.ts:31-39

Timeout Configuration

The timeout is applied using AbortController:

const timer = setTimeout(() => controller.abort(), config.timeoutMs);

With the default of 20000ms (20 seconds), requests exceeding this duration are cancelled and may be retried based on retry configuration.

Sources: src/common/http.ts:44-45

Debug Logging

When JUSTONEAPI_DEBUG is set to true, detailed request information is logged to stderr:

if (config.debug) {
  console.error(`[justoneapi] GET ${toSafeUrlForLog(url)} (attempt ${attempt}/${attempts})`);
}

URL Sanitization

The toSafeUrlForLog() function ensures tokens are never exposed in logs by sanitizing URLs before output.

Sources: src/common/config.ts

Error Handling Integration

Configuration errors are mapped to MCP error codes:

Upstream CodeMCP Error CodeUser Message
-INVALID_TOKENToken is invalid or inactive
-NETWORK_TIMEOUTRequest timed out
-NETWORK_ERRORNetwork connection failed
-INTERNAL_ERRORServer error

Sources: src/common/errors.ts

MCP Server Configuration

Claude Desktop Configuration

{
  "mcpServers": {
    "justoneapi": {
      "command": "npx",
      "args": ["-y", "justoneapi-mcp"],
      "env": {
        "JUSTONEAPI_TOKEN": "your_token_here",
        "JUSTONEAPI_TIMEOUT_MS": "30000",
        "JUSTONEAPI_DEBUG": "true"
      }
    }
  }
}

Configuration File Locations

Operating SystemConfig File Path
macOS~/Library/Application Support/Claude/claude_desktop_config.json
Windows%APPDATA%\Claude\claude_desktop_config.json
Linux~/.config/Claude/claude_desktop_config.json

Sources: README.md

Dependencies

The configuration system depends on the following packages:

PackageVersionPurpose
zod^4.3.4Input validation schemas
dotenv^17.2.3Environment variable loading
@modelcontextprotocol/sdk^1.25.1MCP protocol implementation

Sources: package.json

Startup Validation

The server performs validation at startup in src/index.ts:

async function main() {
  // Validate configuration on startup
  if (!process.env.JUSTONEAPI_TOKEN?.trim()) {
    console.error(
      "[justoneapi-mcp] ERROR: JUSTONEAPI_TOKEN is required but not set.\n" +
        "Please set the JUSTONEAPI_TOKEN environment variable in your MCP host configuration"
    );
    process.exit(1);
  }
  // ... server initialization
}

This ensures users receive immediate feedback about missing configuration before the server attempts any network operations.

Sources: src/index.ts:58-68

Summary

The configuration system provides:

  • Centralized management via environment variables
  • Fail-fast validation on server startup
  • Safe logging with token sanitization
  • Configurable timeouts and retry behavior
  • Debug capabilities for troubleshooting

All configuration flows through a single module (src/common/config.ts) ensuring consistent behavior across the entire application.

Sources: src/index.ts:58-64

MCP Host Integration

Related topics: Getting Started with JustOneAPI MCP

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Components

Continue reading this section for the full explanation and source context.

Section Request Flow

Continue reading this section for the full explanation and source context.

Section Quick Start with npx

Continue reading this section for the full explanation and source context.

Related topics: Getting Started with JustOneAPI MCP

MCP Host Integration

Overview

MCP Host Integration refers to the process of connecting the justoneapi-mcp server to an MCP (Model Context Protocol) host application, enabling AI assistants like Claude Desktop, Cursor, or other MCP-compatible hosts to access Chinese social media search capabilities.

The integration follows the MCP specification, using JSON-RPC over stdio for communication between the host and server. This architecture allows any MCP-compatible host to discover and invoke the tools provided by justoneapi-mcp without custom integrations.

Sources: README.md:1-50

Architecture

System Components

The MCP Host Integration consists of three primary layers:

graph TD
    A["MCP Host<br/>(Claude Desktop, Cursor)"] --> B["justoneapi-mcp Server"]
    B --> C["JustOneAPI Backend"]
    B --> D["Zod Validation Layer"]
    
    A --> E["StdioServerTransport"]
    E --> B
    
    style A fill:#e1f5fe
    style B fill:#fff3e0
    style C fill:#e8f5e9
ComponentDescriptionTechnology
MCP HostClient application providing AI capabilitiesClaude Desktop, Cursor, etc.
TransportCommunication channelstdio (Standard Input/Output)
MCP ServerTool registry and request handler@modelcontextprotocol/sdk
ValidationInput schema validationZod v4
API ClientUpstream API communicationNative fetch with retry logic

Sources: src/index.ts:1-20

Request Flow

sequenceDiagram
    participant Host as MCP Host
    participant Server as justoneapi-mcp
    participant API as JustOneAPI
    
    Host->>Server: Tool invocation (JSON-RPC)
    Server->>Server: Validate with Zod schema
    Server->>API: HTTP request with token
    API->>API: Process search request
    API-->>Server: Raw JSON response
    Server-->>Host: JSON-RPC response

Supported MCP Hosts

The justoneapi-mcp server is compatible with any application implementing the MCP specification:

HostPlatformConfiguration Path
Claude DesktopmacOS, Windows, LinuxPlatform-specific config
CursormacOS, Windows, LinuxMCP settings
Other MCP hostsAnyHost-specific

Sources: README.md:50-80

Installation and Configuration

Quick Start with npx

The recommended installation method uses npx for zero-configuration deployment:

{
  "mcpServers": {
    "justoneapi": {
      "command": "npx",
      "args": ["-y", "justoneapi-mcp"],
      "env": {
        "JUSTONEAPI_TOKEN": "your_token_here"
      }
    }
  }
}

Sources: README.md:60-75

Configuration Variables

VariableRequiredDefaultDescription
JUSTONEAPI_TOKENYes-Your JustOneAPI authentication token
JUSTONEAPI_BASE_URLNohttps://api.justoneapi.comAPI endpoint
JUSTONEAPI_TIMEOUT_MSNo20000Request timeout in milliseconds
JUSTONEAPI_RETRYNo1Number of retries after initial attempt
JUSTONEAPI_DEBUGNofalseEnable debug logging to stderr

Sources: README.md:130-145

Configuration File Locations

Operating SystemConfiguration Path
macOS~/Library/Application Support/Claude/claude_desktop_config.json
Windows%APPDATA%\Claude\claude_desktop_config.json
Linux~/.config/Claude/claude_desktop_config.json

Sources: README.md:55-70

Tool Discovery

Discovery Mechanism

When the MCP host starts, the justoneapi-mcp server automatically registers all available tools. The host queries the server's capabilities and receives a manifest of all callable tools with their input schemas.

graph LR
    A[Host Startup] --> B[Initialize Stdio Transport]
    B --> C[Register Tools via SDK]
    C --> D[Handle list_tools Request]
    D --> E[Return Tool Manifest]
    
    F[User Request] --> G[Validate Input with Zod]
    G --> H[Execute Tool Handler]
    H --> I[Return JSON Response]

Available Tools

Tool NameVersionDescriptionParameters
unified_search_v1v1Multi-platform searchkeyword, source, start, end, nextCursor
kuaishou_search_video_v2v2Kuaishou video searchkeyword, nextCursor

Sources: TOOLS.md:15-50

Discovery Command

To discover available tools in Claude Desktop:

Please list all available tools from justoneapi-mcp

Sources: README.md:35-45

Tool Input Validation

Schema Validation Flow

All tool inputs pass through Zod validation before execution:

graph TD
    A[User Input] --> B[Zod Schema Validation]
    B -->|Valid| C[Execute Tool Handler]
    B -->|Invalid| D[Return VALIDATION_ERROR]
    C --> E[API Request]
    E --> F[JSON Response]
    
    style D fill:#ffcdd2
    style F fill:#c8e6c9

Example: unified_search_v1 Schema

ParameterTypeRequiredDescription
keywordstringYesSearch keyword with syntax support
sourceenumNoPlatform filter (default: ALL)
startstringFirst page*Start time yyyy-MM-dd HH:mm:ss (UTC+8)
endstringFirst page*End time yyyy-MM-dd HH:mm:ss (UTC+8)
nextCursorstringPaginationCursor from previous response

*Required for first page unless using nextCursor

Sources: src/tools/search/unified_search_v1.ts:10-45

Search Syntax Support

OperatorExampleBehavior
Single keyworddeepseekSearch for exact term
ANDdeepseek chatgptBoth terms must appear
ORdeepseek~chatgptEither term can appear
NOTdeepseek -chatgptExclude term

Sources: README.md:95-110

Error Handling Integration

Error Mapping

The server normalizes upstream errors into stable MCP error codes:

Error CodeUpstream ConditionUser Action
INVALID_TOKENInvalid/inactive tokenUpdate JUSTONEAPI_TOKEN
COLLECT_FAILEDData collection failedRetry after delay
RATE_LIMITEDToo many requestsSlow down and retry
DAILY_QUOTA_EXCEEDEDDaily limit reachedWait until tomorrow
INSUFFICIENT_BALANCELow account balanceTop up account
PERMISSION_DENIEDNo access to resourceContact support
VALIDATION_ERRORInvalid parametersCheck input values
INTERNAL_ERRORServer errorRetry later
NETWORK_TIMEOUTRequest timed outCheck network/retry
NETWORK_ERRORConnection failedCheck internet
UPSTREAM_ERRORUnspecified upstream errorRetry or contact support

Sources: src/common/errors.ts:50-80

Error Response Format

ERROR[ERROR_CODE] (upstream=XXX): Human-readable message

Example:

ERROR[RATE_LIMITED] (upstream=302): Rate limit exceeded. Please slow down and retry later.

Sources: README.md:115-125

Retry Logic

The HTTP client implements automatic retry for transient failures:

Retry TriggerBackoff Strategy
AbortError (timeout)250ms × attempt
HTTP 5xx250ms × attempt
ECONNRESET250ms × attempt
ECONNREFUSED250ms × attempt
ENOTFOUND250ms × attempt

Sources: src/common/http.ts:15-30

Session and Pagination

Cursor-Based Pagination

Search results use nextCursor for pagination to maintain state across requests:

graph LR
    A[First Request] -->|start + end| B[Page 1 Response]
    B -->|nextCursor| C[Second Request]
    C -->|nextCursor| D[Page 2 Response]
    D -->|nextCursor| E[Continue...]
    
    style A fill:#e3f2fd
    style D fill:#e8f5e9

Continuing Results

When results have more pages, simply ask:

  • "Show me the next page of results"
  • "Get more results from the previous search"
  • "Continue with the next page"

The MCP host automatically extracts nextCursor and fetches subsequent pages without requiring start, end, or source parameters again.

Sources: README.md:78-92

Dependencies

Runtime Dependencies

PackageVersionPurpose
@modelcontextprotocol/sdk^1.25.1MCP server implementation
zod^4.3.4Schema validation
dotenv^17.2.3Environment configuration

Development Dependencies

PackageVersionPurpose
typescript^5.9.3Type safety
eslint^9.39.2Code linting
prettier^3.7.4Code formatting

Sources: package.json:15-35

Design Philosophy

Transport, Not Transformation

The justoneapi-mcp server adheres to a "Transport, not transformation" principle:

  • Maximum data fidelity - Returns unmodified upstream responses
  • No field parsing - Raw JSON from APIs
  • No data restructuring - Preserves original schema
  • Long-term compatibility - Schema stability over convenience

This ensures that:

  1. No data is lost in translation
  2. Users receive complete API responses
  3. Breaking changes in upstream APIs are visible immediately
  4. Advanced users can access any field from the response

Sources: README.md:155-165

Advanced Configuration Example

{
  "mcpServers": {
    "justoneapi": {
      "command": "npx",
      "args": ["-y", "justoneapi-mcp"],
      "env": {
        "JUSTONEAPI_TOKEN": "your_token_here",
        "JUSTONEAPI_TIMEOUT_MS": "30000",
        "JUSTONEAPI_DEBUG": "true",
        "JUSTONEAPI_RETRY": "3"
      }
    }
  }
}

Sources: README.md:145-155

Token Security

The server masks tokens in log output for security:

function maskToken(token: string): string {
  if (token.length <= 8) return "****";
  return token.slice(0, 4) + "****" + token.slice(-4);
}

Safe URL logging replaces the token parameter with masked value, ensuring credentials are never exposed in logs or error messages.

Sources: src/common/config.ts:30-45

Sources: README.md:1-50

Error Handling

Related topics: HTTP Client Implementation, Unified Search Tool, Configuration Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Related topics: HTTP Client Implementation, Unified Search Tool, Configuration Reference

Error Handling

Overview

The justoneapi-mcp project implements a comprehensive error handling system designed to provide stability, transparency, and raw data fidelity. The error handling layer acts as a bridge between upstream API responses and MCP (Model Context Protocol) tool invocations, normalizing diverse error conditions into stable, actionable MCP error codes.

Key Design Principles:

  • Transport, not transformation — the system prioritizes maximum data fidelity
  • Fail fast with clear validation (token requirement checked early)
  • Retry logic for transient failures
  • Safe logging that never exposes sensitive credentials

Sources: README.md

Sources: README.md

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

medium README/documentation is current enough for a first validation pass.

The project should not be treated as fully validated until this signal is reviewed.

medium Clawhub skill family: 6 SKILL.md files have description-vs-body operation count mismatches (claim vs documented gap of…

The project should not be treated as fully validated until this signal is reviewed.

medium Maintainer activity is unknown

Users cannot judge support quality until recent activity, releases, and issue response are checked.

medium no_demo

The project may affect permissions, credentials, data exposure, or host boundaries.

Doramagic Pitfall Log

Doramagic extracted 7 source-linked risk signals. Review them before installing or handing real data to the project.

1. Capability assumption: README/documentation is current enough for a first validation pass.

  • Severity: medium
  • Finding: README/documentation is current enough for a first validation pass.
  • User impact: The project should not be treated as fully validated until this signal is reviewed.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: capability.assumptions | github_repo:1125683257 | https://github.com/justoneapi/justoneapi-mcp | README/documentation is current enough for a first validation pass.

2. Project risk: Clawhub skill family: 6 SKILL.md files have description-vs-body operation count mismatches (claim vs documented gap of…

  • Severity: medium
  • Finding: Project risk is backed by a source signal: Clawhub skill family: 6 SKILL.md files have description-vs-body operation count mismatches (claim vs documented gap of…. Treat it as a review item until the current version is checked.
  • User impact: The project should not be treated as fully validated until this signal is reviewed.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/justoneapi/justoneapi-mcp/issues/2

3. Maintenance risk: Maintainer activity is unknown

  • Severity: medium
  • Finding: Maintenance risk is backed by a source signal: Maintainer activity is unknown. Treat it as a review item until the current version is checked.
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: evidence.maintainer_signals | github_repo:1125683257 | https://github.com/justoneapi/justoneapi-mcp | last_activity_observed missing

4. Security or permission risk: no_demo

  • Severity: medium
  • Finding: no_demo
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: downstream_validation.risk_items | github_repo:1125683257 | https://github.com/justoneapi/justoneapi-mcp | no_demo; severity=medium

5. Security or permission risk: no_demo

  • Severity: medium
  • Finding: no_demo
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: risks.scoring_risks | github_repo:1125683257 | https://github.com/justoneapi/justoneapi-mcp | no_demo; severity=medium

6. Maintenance risk: issue_or_pr_quality=unknown

  • Severity: low
  • Finding: issue_or_pr_quality=unknown。
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: evidence.maintainer_signals | github_repo:1125683257 | https://github.com/justoneapi/justoneapi-mcp | issue_or_pr_quality=unknown

7. Maintenance risk: release_recency=unknown

  • Severity: low
  • Finding: release_recency=unknown。
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: evidence.maintainer_signals | github_repo:1125683257 | https://github.com/justoneapi/justoneapi-mcp | release_recency=unknown

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 2

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Community Discussion Evidence

Doramagic exposes project-level community discussion separately from official documentation. Review these links before using justoneapi-mcp with real data or production workflows.

Source: Project Pack community evidence and pitfall evidence