# Integration Methods

The Mini-Program AI development mode (hereinafter referred to as "this mode") provides an intelligent runtime environment and development framework. Developers can refer to this document to abstract Mini-Program features into atomic APIs and atomic components based on their business needs, and encapsulate them into SKILLs for Mini-Program AI to invoke.

# 1. Global Prompt

The global prompt is used to describe the overall scope of services provided in this mode, provide relevant background knowledge, behavioral logic, and response style, and guide the Mini-Program AI to generate content such as "guess what you want to ask."

In addition, a Mini-Program may have multiple SKILLs. The relationships and introductions among multiple SKILLs can also be described in the global prompt to help the model select the appropriate SKILL and atomic APIs to serve users.

The global prompt is typically a file named AGENTS.md, whose path can be specified in app.json:

// app.json
{
  "agent": {
    "skills": [],
    "instruction": "path/to/AGENTS.md"
  }
}

The instruction field is currently optional, and the maximum file size is 10000 bytes.

# 2. SKILL Declaration

A Mini-Program can declare multiple SKILLs. SKILLs must be encapsulated in Independent Subpackages. One Independent Subpackage can contain multiple SKILLs, and Lazy Code Loading (lazyCodeLoading) must be globally enabled.

Add the agent field in app.json to declare the SKILL list (agent.skills). The fields for each SKILL are described as follows:

Field Required Description
name Yes SKILL name
description Yes Brief description of the SKILL
path Yes SKILL Subpackage path (absolute path)
// app.json
{
  "lazyCodeLoading": "requiredComponents",
  "subPackages": [
    {
      "root": "path/to/pkg",
      "independent": true,
      "pages": []
    }
  ],
  "agent": {
    "skills": [
      {
        "name": "weatherSkill",
        "description": "Weather query business",
        "path": "path/to/pkg/weatherSkill"
      },
      {
        "name": "shoppingSkill",
        "description": "Shopping business",
        "path": "path/to/pkg/shoppingSkill"
      }
    ]
  }
}

# 3. SKILL Encapsulation

A SKILL contains business documentation (SKILL.md), declarations of model-invocable capabilities (mcp.json), implementations of atomic APIs (apis/), and atomic components (components/). The directory structure is as follows:

File Description Required
SKILL.md Detailed description of the SKILL. Only a single file is supported; referencing other md files is not supported. Maximum 16000 bytes Yes
index.js Registers all atomic APIs involved in the current SKILL Yes
mcp.json Declarations of model-invocable capabilities (declarations of all atomic APIs in the current SKILL). Maximum 24000 bytes Yes
components/ Directory containing atomic component code implementations No, provided as a suggestion only
apis/ Directory containing atomic API code implementations No, provided as a suggestion only

Please Note

When calculating the length of mcp.json, all outputSchema fields, spaces, and line breaks are removed first before calculation.

|-- path/to/pkg/weatherSkill
|   |-- SKILL.md
|   |-- mcp.json
|   |-- components/
|   |-- apis/
|   |-- index.js

# 3.1 Declarations of Model-Invocable Capabilities

mcp.json contains the Schema declarations of all atomic APIs. componentPath indicates that the return result of the atomic API can be rendered as a card by an atomic component; inputSchema and outputSchema must follow the JSON Schema specification.

Property Required Description
name Yes Identifier, must match the atomic API function name exported in index.js
description Yes Functional description of the atomic API
inputSchema Yes Input parameter Schema of the atomic API, must be in object format
outputSchema Recommended Schema corresponding to the structuredContent returned by the atomic API
_meta No Can specify the atomic component to render and the handoff page. componentPath is relative to the SKILL directory, e.g., { "ui": { "componentPath": "path/to/comp" } }

Below is a declaration example containing only one getWeather atomic API:

{
  "apis": [
    {
      "name": "getWeather",
      "description": "Query the weather at the current location or a certain place for a future period",
      "_meta": {
        "ui": {
          "componentPath": "path/to/comp",
          "pagePath": "path/to/page"
        }
      },
      "inputSchema": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The location to query weather for, such as city name, administrative district name, or latitude/longitude. Defaults to the current location if not provided"
          },
          "days": {
            "type": "number",
            "description": "Number of forecast days, range 1-15, default 7"
          }
        },
        "required": ["days"]
      },
      "outputSchema": {}
    }
  ]
}

# Handling Image/File Content

The Mini-Program AI input box supports multimodal upload, allowing users to send images/files to the Mini-Program AI. If you need to handle user-uploaded images/files, you can mark "format": "image" | "file" in the inputSchema field of the atomic API declaration. The Mini-Program AI will invoke the corresponding atomic API and pass the received image/file to the corresponding field.

{
  "name": "EditPhoto",
  "description": "Help users edit photos",
  "inputSchema": {
    "type": "object",
    "properties": {
      "imagePath": {
        "type": "string",
        "description": "Local image path",
        "format": "image"
      },
      "query": {
        "type": "string",
        "description": "User's photo editing requirements"
      }
    },
    "required": ["imagePath", "query"]
  }
}

# 3.2 Atomic API Implementation

Taking the atomic API getWeather as an example, its return values are described as follows:

Property Type Required
isError boolean No, defaults to false
content ContentBlock[] Yes, text content returned to the LLM, no more than 200 KB
structuredContent Record No, structured data returned to the LLM, no more than 200 KB
handoff HandoffResolver No, data for handoff to the Mini-Program page, see "Handoff to Mini-Program Page"
_meta Record No, invisible to the LLM, can carry metadata, no more than 200 KB
apiCalls { name: string; arguments: Record }[] No, explicitly specifies the atomic API to invoke next

Among these, the data of the three fields isError, structuredContent, and content will serve as the LLM's context for the model to understand; the content of _meta is invisible to the LLM and is used to carry private data and pass it to atomic components.

  • When isError: true, GUI card rendering will not be performed, structuredContent will be ignored, and content is typically used for guiding exception flows.
  • When isError: false and the atomic API is bound to an atomic component, the Mini-Program AI will tend to render a GUI card. The data of structuredContent will be passed to the atomic component for rendering (to help the model understand the card content), and content is used for subsequent flow guidance. To force the display of a GUI card, you can append guidance in content, for example: "Next, display the XXX UI card to the user."

ContentBlock[] currently only supports text content, defined as follows:

interface TextContent {
  type: "text";
  text: string;
}

HandoffResolver is defined as follows:

type HandoffResolver = (data: {
  result: {
    isError: boolean;
    content: ContentBlock[];
    structuredContent: Record<string, unknown>;
    _meta: Record<string, unknown>;
  };
}) => { query: string; payload: Record<string, unknown> };

In the internal implementation of an atomic API, you can request data from the developer's own server via ft.request, or obtain data by calling cloud functions or databases via cloud development APIs.

Below is a code implementation example of getWeather:

async function getWeather({ location, days }) {
  // Internal implementation of the atomic API, omitted here
  // ft.request({ url: 'https://www.example.com/get_weather' })
  return {
    isError: false,
    content: [{ type: "text", text: "Weather for Beijing for the next 3 days has been retrieved for you" }],
    structuredContent: {
      location: "Beijing",
      forecasts: [
        { date: "2026-04-23", dayWeather: "Sunny", tempHigh: 28, tempLow: 14 },
        { date: "2026-04-24", dayWeather: "Cloudy", tempHigh: 25, tempLow: 13 },
        { date: "2026-04-25", dayWeather: "Light Rain", tempHigh: 20, tempLow: 12 }
      ]
    }
  };
}

# Explicitly Specifying the Atomic API to Invoke Next

In certain scenarios with relatively fixed flows, it is necessary to explicitly trigger the next atomic API after one atomic API call is completed. In this case, you can explicitly specify the atomic API to invoke (apiCalls) in the return value to reduce the time consumed by model inference.

ft.modelContext.registerAPI('placeOrder', async ({ skuId, count }) => {
  const loggedIn = await checkUserLogin();
  // Not logged in: instruct the next step to invoke login
  if (!loggedIn) {
    return {
      isError: false,
      content: [{ type: 'text', text: 'User is not logged in' }],
      apiCalls: [{ name: 'login', arguments: {} }]
    };
  }
  // Logged in: place order normally
  const order = await createOrder({ skuId, count });
  return {
    isError: false,
    content: [{ type: 'text', text: 'Order has been created' }]
  };
});

# 3.3 Registering Atomic APIs

Registration is performed in the index.js of the SKILL directory. When the Mini-Program AI initiates an atomic API call, it will find the corresponding function entry in the registration list and execute it:

const getWeather = require('./apis/getWeather');
const skill = ft.modelContext.createSkill('/path/to/pkg/weatherSkill');
// name must match the one declared in mcp.json
skill.registerAPI('getWeather', getWeather);

# Middleware Mechanism

To facilitate reusing common logic across multiple atomic APIs, this mode provides an atomic API middleware mechanism, which can be used for scenarios such as unified login state, unified reporting, and error monitoring.

ft.modelContext.createSkill(skillPath: string); // Create a skill; skillPath must match agent.skills[].path in app.json
skill.use(Middleware);                          // Register middleware
skill.registerAPI(name, handler);               // Register an atomic API, equivalent to ft.modelContext.registerAPI('name', handler)

interface MiddlewareContext {
  name: string;                   // Name of the currently executing atomic API
  skillPath: string;              // The skill in which the middleware is executing
  arguments: Record<string, any>; // Arguments of the atomic API
}

type Middleware = (ctx: MiddlewareContext, next: () => Promise<void>) => Promise<void>;

Example:

const skill = ft.modelContext.createSkill('path/to/pkg/weatherSkill');
skill.registerAPI('getWeather', getWeather);
skill.use(async (ctx, next) => {
  // 1. Unified login (first time only)
  const token = ft.getStorageSync('token');
  if (!token) {
    const { code } = await ft.login();
    const res = await ft.request({ url: '...', data: { code } });
    ft.setStorageSync('token', res.data.token);
    // You can also throw an error directly to let the Mini-Program AI follow other processing flows
  }
  // 2. Reporting: record the start time
  const start = Date.now();
  try {
    await next(); // Execute the actual atomic API handler
    reportLog({ name: ctx.name, cost: Date.now() - start });
  } catch (err) {
    // 3. Unified error monitoring
    reportError({ name: ctx.name, error: err, cost: Date.now() - start });
    throw err;
  }
});

Core semantics:

  • The middleware is executed on every atomic API call;
  • Code before next() is pre-logic, and code after next() is post-logic; errors can be caught with try/catch;
  • The entire middleware chain and the atomic API execution share the same timeout limit (currently 300s);
  • Multiple middleware can be registered, forming a call chain in registration order: outer → inner → handler → inner → outer;
  • Middleware functions must be async; the runtime will await the entire chain.

# 3.4 Handoff to Mini-Program Pages

There are two ways to present the structured data returned by atomic APIs, one of which is the Mini-Program page: during a conversation flow, the data returned after an atomic API is called is passed into a Mini-Program page, handing off the conversation flow to the Mini-Program page to seamlessly continue the current flow state.

Please note

If you only need to provide a detail entry in the reply text without handing off the entire current conversation flow into a page, you should use format: "page-link" in outputSchema (see "Text with Inline Links") instead of returning handoff. The two capabilities can coexist and do not replace each other.

The implementation consists of the following three steps:

1. Declare the pagePath corresponding to the atomic API in mcp.json

{
  "apis": [
    {
      "name": "getWeather",
      "_meta": {
        "ui": {
          "pagePath": "/path/to/page"
        }
      }
    }
  ]
}

Please note

pagePath does not currently support dynamic changes.

2. The atomic API returns a handoff object

Carry a handoff object in the atomic API return value, at the same level as the content / structuredContent fields. handoff contains the query and payload fields: query together with the preceding pagePath constructs the link to open the Mini-Program page, while payload is passed to the Mini-Program via the ft.onAgentHandoff API.

Field Required Description
path No Allows dynamically specifying the page path
query No Page query string, obtained by the Mini-Program page via the Page's onLoad and ft.onAgentHandoff
payload No Can pass the business data returned by the atomic API, used by the Mini-Program page to synchronize the corresponding flow state, obtained via ft.onAgentHandoff
async function getWeather({ location, days }) {
  // Internal implementation of the atomic API, omitted here
  return {
    isError: false,
    content: [{ type: "text", text: "I've retrieved the weather for Beijing for the next 3 days" }],
    structuredContent: {},
    handoff: (data) => {
      // data.result.structuredContent is the data filtered by the model based on user intent
      // If query contains special characters, developers need to encodeURIComponent themselves
      return {
        query: `poi=${encodeURIComponent('Beijing')}`,
        payload: {
          location: 'Beijing',
          forecasts: [
            { date: "2026-04-23", dayWeather: "Sunny", tempHigh: 28, tempLow: 14 },
            { date: "2026-04-24", dayWeather: "Cloudy", tempHigh: 25, tempLow: 13 }
          ]
        }
      };
    }
  };
}

3. The Mini-Program listens to ft.onAgentHandoff to obtain the handoff data

The Mini-Program obtains the handoff data passed by the atomic API via ft.onAgentHandoff, synchronizing the page to the corresponding flow state; when necessary, it also needs to synchronize the page stack corresponding to the business flow into an appropriate state.

API Description
ft.onAgentHandoff(callback) Triggered when entering by tapping the Mini-Program card
ft.offAgentHandoff(callback) Cancel listening

Callback parameters:

{
  pageId: number  // Target page instance ID, used to precisely deliver the payload to the associated page
  path: string    // path of the currently opened page (excluding query)
  query: string   // Page query string, same as the handoff.query returned by the atomic API
  payload: unknown // handoff.payload returned by the atomic API
}

Code example:

App({
  onLaunch() {
    ft.onAgentHandoff(({ pageId, path, query, payload }) => {
      this.globalData.agentHandoffs = this.globalData.agentHandoffs || {};
      this.globalData.agentHandoffs[pageId] = { path, query, payload };
    });
  }
});

Page({
  onLoad(query) {
    const handoffs = getApp().globalData.agentHandoffs || {};
    const handoff = handoffs[this.getPageId()];
    delete handoffs[this.getPageId()];
    // Use the data returned by the atomic API to update the page state
    this.setData({ forecasts: handoff.payload.forecasts });
    // Use the query parameters to fetch data; if the query submitted by handoff was encoded, you need to decode it here yourself
    const parsedPoi = decodeURIComponent(query.poi);
    this.loadPoiDetail(parsedPoi).then((forecasts) => this.setData({ forecasts }));
  }
});

# 3.5 Atomic Component Implementation

Please note

Atomic components currently do not support debugging.

# 3.5.1 Atomic Component Definition

Atomic components are used to present the structured data returned by atomic APIs. In terms of coding, they are consistent with the Mini-Program's Custom Components, but note that atomic components cannot be declared as virtual components.

Via ft.modelContext.getContext / getViewContext, you can obtain information such as the dimensions and data needed for rendering the atomic component:

Component({
  lifetimes: {
    created() {
      const modelCtx = ft.modelContext.getContext(this);
      const { NotificationType } = ft.modelContext;

      modelCtx.on(NotificationType.Input, (data) => {
        // Input data of the atomic API
      });
      modelCtx.on(NotificationType.Result, (data) => {
        // Output data of the atomic API
      });

      const viewCtx = ft.modelContext.getViewContext(this);
      const { minHeight, maxHeight, width } = viewCtx.getDimensions();
      viewCtx.on(NotificationType.Overflow, (data) => {
        // data.contentHeight: total content height
        // data.overflowHeight: overflow height
        // data.maxHeight: the hard threshold of the current card container
        // Note: if you set maxHeight and overflow: hidden on the component's root node, it will not be triggered
      });
    }
  }
});

# 3.5.2 Associating a Mini-Program Page (Required)

The GUI card rendered by the atomic component has a Title Bar above it, with an entry to the Mini-Program provided at its top right. This entry must be configured with a Mini-Program page associated with the atomic component.

The implementation consists of two steps:

1. Declare the complete path (fixed path) of the Mini-Program page corresponding to the atomic component in mcp.json:

{
  "apis": [],
  "components": [
    {
      "path": "path/to/comp",
      "relatedPage": "/path/to/related-page"
    }
  ]
}

2. Dynamically set the page's query parameters when the atomic component renders:

Component({
  lifetimes: {
    created() {
      const modelCtx = ft.modelContext.getContext(this);
      this._viewCtx = ft.modelContext.getViewContext(this);
      modelCtx.on('result', (data) => {
        const { orderId } = data.result.structuredContent;
        this.setData({ orderId });
        // If only query is passed, the path is determined by components[].relatedPage in mcp.json
        this._viewCtx.setRelatedPage({ query: `orderId=${orderId}` });
        // If the atomic component may be associated with multiple Mini-Program pages, you can also pass the path parameter
        // this._viewCtx.setRelatedPage({ path: '/path/to/page', query: `orderId=${orderId}` })
      });
    }
  },
  methods: {
    onSpecChange(e) {
      const spec = e.detail.value;
      this.setData({ selectedSpec: spec });
      // Update the query parameters after the state changes
      this._viewCtx.setRelatedPage({
        query: `orderId=${this.data.orderId}&spec=${spec}`
      });
    }
  }
});

# 3.5.3 Constraints of Atomic Components

The runtime environment of atomic components is isolated from the atomic interface, residing in different contexts, and the interface capabilities they can invoke also differ. Atomic components have the following characteristics and limitations:

  • Limited rendering area: the width varies with the screen width, the minimum height is an aspect ratio of 4:1, and the maximum height is an aspect ratio of 1:1. When not exceeding the minimum/maximum height, it automatically expands with the content;
  • The card height is determined at initialization and cannot be changed afterward;
  • Only tap click, image load, and image error events are supported; other interaction events are not supported;
  • Network requests and cloud development interfaces are not supported by default; they must be declared as a "Real-time Dynamic Component";
  • Timer interfaces (such as setTimeout, setInterval) are not supported by default; they must be declared as a "Real-time Dynamic Component";
  • Interfaces for opening Mini-Programs are not supported;
  • Animations are not supported;
  • Up-and-down scrolling is prohibited (i.e., overflow-y is prohibited);
  • Supports clicking a descendant to send an upward text message on behalf of the user (ModelContext.sendFollowUpMessage), with the same effect as the user sending a text message;
  • Supports opening a half-screen page after clicking (see "Half-screen Page").

# 3.5.4 Real-time Dynamic Component

For reasonable scenarios that need to display real-time dynamic content, the real-time dynamic capability can be declared in mcp.json (supporting ft.request, timers, and other interfaces).

{
  "apis": [],
  "components": [
    {
      "path": "path/to/comp",
      "permissions": {
        "scope.dynamic": {
          "desc": "Declare the usage scenario"
        }
      }
    }
  ]
}

# 3.5.5 Expired State of Atomic Components

Supports marking an already rendered atomic component as expired through an interface, preventing the user from clicking it again.

1. Component Expiration Declaration

Declare under the components field in mcp.json:

Field Type Required Description
path string Yes Component path (relative to the SKILL directory)
expirable boolean No Declares whether the card rendered by this component can be marked as expired; default false
expiredText string No The text displayed after expiration; default "Service expired"
{
  "apis": [
    {
      "name": "searchRides",
      "description": "Search for ride-hailing options",
      "_meta": { "ui": { "componentPath": "components/ride-card/index" } },
      "inputSchema": {}
    }
  ],
  "components": [
    {
      "path": "components/ride-card/index",
      "expirable": true,
      "expiredText": "Store closed"
    }
  ]
}

2. Component Expiration Interfaces

Two granularities of expiration APIs are provided:

Method 1: ft.modelContext.expireAllCards()

ft.modelContext.expireAllCards(): Promise<{ errMsg: string }>

Can be called in an atomic interface or an atomic component. All components declared with expirable: true (including itself) will be marked as expired and rendered with an overlay. It also supports filtering by componentPath, causing all atomic components with the same componentPath, or the most recent atomic component with a specific componentPath, to expire:

// Expire cards of a specific component (absolute path)
ft.modelContext.expireAllCards({
  componentPaths: ['pkgA/weatherSkill/components/weather-card/index']
});
// Expire only the most recent matching card
ft.modelContext.expireAllCards({
  componentPaths: ['pkgA/weatherSkill/components/weather-card/index'],
  match: 'latest'
});

Method 2: ft.modelContext.getViewContext(this).expirePreviousCards()

const viewCtx = ft.modelContext.getViewContext(this);
viewCtx.expirePreviousCards(): Promise<{ errMsg: string }>

Can only be called within an atomic component. Previously rendered atomic components declared with expirable: true will be marked as expired and rendered with an overlay. It also supports filtering by componentPath.

3. Component Expiration Event

When an atomic component is marked as expired, it receives an expiration event, at which point the component can perform necessary cleanup internally:

Component({
  lifetimes: {
    created() {
      const { NotificationType } = ft.modelContext;
      const viewCtx = ft.modelContext.getViewContext(this);
      viewCtx.on(NotificationType.Expire, (event) => {
        console.log('Card expired', event.expiredText);
        // Cleanup logic such as stopping polling, disabling buttons, etc.
      });
    }
  }
});

# 3.5.6 Syncing Interaction State to the Model

When the user performs interactive operations on an atomic component card (such as clicking a button, selecting an option, etc.) that modify the card state, the state change can be synced to the model through the updateModelContext interface, so that the model is aware of the user's latest selection and can respond accordingly.

Component({
  methods: {
    onOptionSelect(e) {
      const { option } = e.currentTarget.dataset;
      // Sync the user's selection to the model
      const viewCtx = ft.modelContext.getViewContext(this);
      viewCtx.updateModelContext({
        content: [{ type: 'text', text: `User selected ${option}` }]
      });
    }
  }
});

Parameter description:

Parameter Type Required Description
content Array<{ type: 'text', text: string }> Yes Array of content blocks; currently only the text type is supported
© FinClip with ❤ , Since 2017