SuperAPI AI Directory

wxa-ai-mode-dev

Agents & models

View repository

Updated 10-16 02:57

About this skill

Mini Program AI Development Mode (beta) Development Guide

Mini Program AI development mode (hereinafter referred to as this mode) provides a set of intelligent runtime environment and development framework. Developers abstract Mini Program features intoatomic interfaces (API)andatomic components (Component), encapsulate them into SKILL, for Mini Program AI to call.

When a user initiates a conversation through Mini Program AI, Mini Program AI usesMini Program MCP protocolto select appropriate atomic interfaces and atomic components, complete data processing and task execution, and finally display the results as GUI cards. User identity remains consistent with the original Mini Program (login credentials can be shared via storage).

Currently in beta testing phase, code submission for review is not yet open. Only supports iOS (WeChat ≥8.0.74), base library ≥3.16.1.Do not merge AI mode code into the official version for submission and review.

Responsibility Boundaries

  • ✅ Provide complete technical specification reference for AI development mode
  • ✅ Define design specifications, best practices, and prohibitions for atomic interfaces/components
  • ✅ Define content text writing, description three-part template, attention weight principles
  • ✅ Provide complete guidance for onboarding configuration, debugging process, and FAQ
  • ❌ Does not generate business atomic interface/component code (handled by wxa-skills-generate)
  • ❌ Does not perform validation and repair (handled by wxa-skills-validate)
  • ❌ Does not perform end-to-end evaluation (handled by wxa-skills-eval)
  • ❌ Does not create new Mini Program projects (handled by wxa-create-ai-miniprogram)
  • 📦 Deliverables: reference documentation + specification description

Terminology Conventions

Concept Description
Mini Program MCP A protocol that exposes callable capabilities to Mini Program AI. Unlike standard MCP, it adapts to Mini Program development characteristics
Atomic interface (API) The smallest execution unit, encapsulating a single business function, with standardized input/output, running on the WeChat clientIndependent JS environment
Atomic component (Component) The visual display unit of an atomic interface, rendering structured data as GUI cardsdisplayed in the conversation flow
SKILL Complete capability encapsulation for specific scenario tasks, including SKILL.md、mcp.json, atomic interface implementation, and atomic component implementation

Reference Material Index

Source Purpose Loading Timing
wxa-skills-generate/SKILL.md Code generator workflow When code generation is needed
wxa-skills-validate/SKILL.md Validator workflow and repair process When validation is needed
wxa-skills-eval/SKILL.md How to use the evaluation engine When evaluation is needed

Core Concepts

Three-layer architecture and data transfer

[原子接口上下文 A] ──── 返回值(content/structuredContent/_meta) ────→ [小程序 AI 后台]
[原子组件上下文 B] ─┐
[实时动态组件上下文 C]┘ 三个上下文全局变量不共享,数据只能通过返回值传递
[半屏页面] ───────── 与小程序运行环境一致,部分接口受限
Return value fields LLM visible Purpose
content ✅ Context and instructions for LLM decision-making (TextContent[], ≤200KB)
structuredContent ✅ Structured data for the LLM to understand the content displayed on the screen (≤200KB)
_meta ❌ Pure rendering data, such as image URLs, invisible to the LLM (≤200KB)

Integration method (key code)

1. Global configuration app.json

{
  "lazyCodeLoading": "requiredComponents",
  "subPackages": [
    {
      "root": "path/to/pkg",
      "independent": true,
      "pages": []
    }
  ],
  "agent": {
    "skills": [
      {
        "name": "weather",
        "description": "查询天气业务",
        "path": "path/to/pkg/weather-skill"
      }
    ],
    "instruction": "path/to/AGENTS.md",
    "pageMetadata": "path/to/page-meta.json"
  }
}

Constraints:

  • SKILL must be placed inan independent subpackage(independent: true)
  • must be enabled lazyCodeLoading: "requiredComponents"
  • A maximum of 30 SKILLs
  • A SKILL can only be in one subpackage

2. SKILL directory structure (fixed)

skills/<skill-name>/
├── SKILL.md         # 业务说明(固定文件名,≤16000 字节)
├── mcp.json         # 原子接口声明(固定文件名,≤24000 字节,不计 outputSchema)
├── index.js         # 注册入口(固定文件名)
├── apis/            # 原子接口实现(建议目录)
└── components/      # 原子组件实现(建议目录)

3. Atomic interface implementation specification

async function myAPI({ param1, param2 }) {
  // 业务逻辑...
  return {
    isError: false,    // 是否出错(isError=true 时不渲染卡片)
    content: [
      { type: "text", text: "事实陈述 + 业务动作引导" }
    ],
    structuredContent: {
      // 供 LLM 理解卡片内容的字段(不放图片 URL)
    },
    _meta: {
      // LLM 不可见的私有数据(如图片 URL、后台多余字段)
    }
  }
}

4. Registration entry index.js

const skill = wx.modelContext.createSkill('/path/to/pkg/my-skill')

// 注册原子接口
skill.registerAPI('getData', require('./apis/getData'))
skill.registerAPI('searchItems', require('./apis/searchItems'))

// 中间件(洋葱模型,用于统一登录、上报、错误监听等)
skill.use(async (ctx, next) => {
  const start = Date.now()
  try {
    await next()
  } catch (err) {
    reportError({ name: ctx.name, error: err })
    throw err
  }
})

5. mcp.json Capability declaration

{
  "apis": [
    {
      "name": "getWeather",
      "description": "查询天气。按位置和天数查询未来天气。\n调用时机:用户询问天气时。\n【严禁场景】不要用于查询历史天气。",
      "inputSchema": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "要查询天气的地点名(用户原话中的地点)。【禁止编造】用户未提及时禁止填写,应反问『请问您想查哪个城市的天气?』"
          },
          "days": {
            "type": "number",
            "description": "预报天数,范围1-15。用户未提及时默认填7。"
          }
        },
        "required": ["days"]
      },
      "outputSchema": {},
      "_meta": { "ui": { "componentPath": "components/weather-card/index" } }
    }
  ],
  "components": [
    {
      "path": "components/weather-card/index",
      "relatedPage": "/pages/weather/detail"
    }
  ]
}

Interfaces that handle images/files need to add inputSchema to the corresponding field in "format": "image" or "format": "file"。

6. Atomic component implementation

Component({
  lifetimes: {
    created() {
      const modelCtx = wx.modelContext.getContext(this)
      const viewCtx = wx.modelContext.getViewContext(this)
      const { NotificationType } = wx.modelContext

      // 监听原子接口返回结果
      modelCtx.on(NotificationType.Result, (data) => {
        const sc = data.result.structuredContent
        const meta = data.result._meta
        this.setData({ ...sc, ...meta })
      })

      // 必须设置关联小程序页面
      viewCtx.setRelatedPage({ query: `id=${this.data.id}` })

      // 监听溢出/过期事件
      viewCtx.on(NotificationType.Overflow, (data) => { /* 内容溢出 */ })
      viewCtx.on(NotificationType.Expire, (event) => { /* 清理逻辑 */ })
    }
  },
  methods: {
    onTap() {
      // 代用户上行消息(等效于用户发送),可附带 api/call 指定下一步原子接口
      this._modelCtx.sendFollowUpMessage({
        content: [
          { type: 'text', text: '选择拿铁' },
          { type: 'api/call', data: { name: 'selectDrink', arguments: { drinkId: 123 } } }
        ]
      })
      // 打开半屏页面(原子接口内不可调用)
      this._viewCtx.openDetailPage({ url: '/package/pages/detail?drinkId=123' })
    }
  }
})

7. page-meta.json Text link metadata

{
  "pages": [
    {
      "path": "pages/detail/detail",
      "name": "商品详情",
      "description": "展示特定商品的信息",
      "query": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "description": "商品的唯一标识符" }
        },
        "required": ["id"]
      }
    }
  ]
}

≤8000 bytes. Text links area fallback strategy, and core functionality should be closed-loop within the AI.

8. Mini Program ↔ Mini Program AI interaction interface

  • wx.openAgent({ followUpMessage, context }) — Open the AI interface
  • wx.navigateBackAgent({ followUpMessage, context }) — Return to the AI interface from a text link/related page
  • wx.checkIsSupportAgent() — Determine whether the current device supports it
  • wx.onAgentOpen(callback) — Listen for the user opening the AI interface from the capsule

New API quick reference (all under wx.modelContext )

Atomic interface environment

API Description
wx.modelContext.createSkill(path) Create a Skill instance
skill.registerAPI(name, handler) Register an atomic interface
skill.use(middleware) Register middleware (onion model)
wx.modelContext.getSessionId() Get the session ID
wx.modelContext.expireAllCards({ componentPaths, match }) Set component expiration

Atomic component environment

API Description
wx.modelContext.getContext(this) Get ModelContext
wx.modelContext.getViewContext(this) Get ViewContext
modelCtx.sendFollowUpMessage({ content }) Send an uplink message on behalf of the user
viewCtx.openDetailPage({ url }) Open a half-screen page
viewCtx.preloadDetailPage({ url }) Preload a half-screen page
viewCtx.setRelatedPage({ path, query }) Set the related Mini Program page (required)
viewCtx.expirePreviousCards({ componentPaths, match }) Component card before expiration
viewCtx.getDimensions() Get card size ({ minHeight, maxHeight, width })
viewCtx.on(NotificationType, callback) Listen for Input / Result / Overflow / Expire events

Atomic component constraints (hard rules)

  • Card width is fixed with the screen, height is at least 4:1 and at most 1:1; the height is determined at initialization and subsequentlyimmutable
  • Only supports tap tap click events, image load/error events
  • By defaultdoes not supportnetwork requests and timers; if support is needed, declare permissions: { "scope.dynamic": { "desc": "..." } } as a real-time dynamic component
  • Does not support animations, vertical scrolling is prohibited (overflow-y)
  • must be configured relatedPage(related Mini Program page), in mcp.json the components[].relatedPage declare a fixed path in components[].relatedPage, and in the component created set the dynamic query via setRelatedPage Set dynamic query
  • Does not support wx.navigateTo and other page routing interfaces

WXSS support scope (atomic component rendering engine differences)

  • Selectors: only class selectors, ID selectors, tag selectors, and descendant selectors are supported (class selectors are recommended)
  • Units:px、vw、rpx、em、rem
  • Supports @media (prefers-color-scheme: dark) dark mode adaptation
  • Flex layout is fully supported; display supports flex/block/inline/none
  • Design specifications: recommended corner radius 4px, screen margin 16px, content outer margin 6px, content inner padding 9px or 16px
  • Fonts: title 17, body 15, annotation 12, maximum no more than 36, minimum 12

Built-in component support scope

Component Description
view Fully supported
text user-select not supported
map Drag and zoom interactions not supported
button All open-type not supported
image Network addresses only, png/jpg only
canvas 2d only
scroll-view Horizontal scrolling only (scroll-x)

Best practices (core specifications)

Attention weight principle

LLMs do not distribute attention evenly across different information sources; arrange by priority:

Priority Information source Role
★★★★★ Returned by the atomic interface content Closest to the decision point; the LLM understands it as "factual continuation + direct instruction"
★★★★ mcp.json of description The first sentence determines interface selection accuracy
★★★★ inputSchema field description Core reference for parameter filling
★★★ SKILL.md Business process orchestration, cross-interface rules, intent routing

When multiple constraints conflict, the LLM follows instructions at higher-weight positions. Core constraints should not all rely on SKILL.md, hard constraints should be specified through the content or description field.

Content division of labor

Position What to put
content Result of this call + next action
mcp.json description Interface function, when to call, strictly prohibited scenarios
inputSchema description Parameter semantics and value constraints
SKILL.md Cross-interface rules, intent routing, business process orchestration

Three-part template for the field description (must be strictly followed)

<字段语义(一句话)>。
取值来源:<用户原话 / 上游接口 X 返回的 Y 字段 / 枚举集合>。
【禁止编造】<用户未提供 / 上下文无来源 / 越界> 时,<反问用户『…』 / 改走接口 Z / 留空>。

None of the three parts may be missing: the first two parts determine whether the model can fill it in correctly, and the third part determines that the model will not "force-fill".

How to write the content text

✅ Correct: two-part format of factual statement + business action

"已查到该 orderId 的机票订单数据。请把本次接口返回的卡片数据展示给用户,并用简短一句话引导用户查看。"
"用户当前授权状态:手机号=未授权,定位=已授权。下一步允许的动作:把手机号授权确认卡片展示给用户,等用户在卡片中亲自点击同意后才能进入下一步。"

❌ Counterexample: bare instruction

"接下来请务必为用户展示订单确认卡片"

With only an action and no facts, the model may skip waiting for the user's decision.

Common prohibitions (declared in SKILL.md)

  • Bare instructions prohibited: all interfaces that return successfully (isError=false) and are bound to components,must display a card, and it is prohibited to list card detail data as plain text
  • ID fabrication prohibited:drinkId / orderId / itemId etc. must come from the original values returned by upstream interfaces
  • Concurrent calls to payment-type interfaces prohibited:payOrder / createOrder must wait until the previous transaction ends before initiating
  • It is prohibited to put image URLs in structuredContent Place image URL in the middle
  • Action-type interfaces must be called successfully first (isError=false) before announcing the result to the user
  • Enumeration values must use English enums; Chinese labels are prohibited

How to write the business SOP in SKILL.md

SKILL.md Carries the business-level SOP, including four parts:

  1. Complete business process diagram(ASCII flowchart; interface names must exactly match the mcp.json of name )
  2. Atomic interface dependency relationship table(interface name, role, component, preconditions)
  3. Business constraints(ironclad rules such as output form, execution order, concurrency vs. serial, data sources, etc.)
  4. User intent routing table(direct intent trigger words + intent routing rules)

Note:

  • Do not repeat mcp.json 's description and inputSchema
  • Do not write specific URL literals in SKILL.md (the model will copy them verbatim)
  • The fallback action for ambiguous short expressions is uniformly "ask for clarification first"

Debugging and evaluation

  • Developer tools: download the latest Nightly Electron Build, switch to "Mini Program AI Compilation" mode, and switch the base library to 3.16.1
  • Real device preview: iOS WeChat ≥8.0.74, enter "Mini Program AI Development Mode" from the top-right of the capsule, supports opening vConsole for debugging
  • Generate SKILL: install wxa-skills-generate, enter "Help me analyze this project and integrate WeChat Mini Program AI Development Mode" to activate the generation process
  • Validate SKILL: install wxa-skills-validate, automatically render and validate execution
  • Evaluate SKILL: install wxa-skills-eval, simulate real user conversations, automatically analyze issues, and output eval_report.html

Before using the validation and evaluation tools, you must enable the service port in WeChat DevTools under "Settings → Security Settings".


Common limitations and FAQ quick reference

  • Only iOS WeChat ≥8.0.74 supports real devices; Android/HarmonyOS are not supported for now
  • AI replies do not support streaming output
  • AI replies support only two formats: plain text, or the fixed "text + card" format
  • Supports multimodality: users can send images/files, and the interface can declare "format": "image" or "format": "file"
  • The maximum timeout for atomic interfaces is 300s (including the middleware chain)
  • Half-screen pages prohibit all jump, routing, and advertising interfaces
  • If you need to make network requests in an atomic component, it must be declared as a real-time dynamic component (scope.dynamic)
  • uni-app projects need to use patch-package to patch @dcloudio/uni-mp-weixin, and patch in modelContext

Related links