App Intents と AppFunctions の書き方
iOS の App Intents と Android の AppFunctions で、アプリの操作を Siri やシステムのエージェントに公開する書き方のメモです。数値を記録するトラッカーアプリ(架空)を例に、同じ4つの操作を両方の OS に出すときの書き方と注意点をまとめます。アプリは Kotlin Multiplatform(KMP)で作っていて、操作は共通モジュールの Kotlin に置き、iOS からは KMP が出力する framework 経由で呼んでいます。2026年11月7日時点の情報です。
TL;DR
- 操作そのものは KMP の共通モジュールに置き、App Intents と AppFunctions はそれを呼ぶだけの薄い層にします。
- AppFunctions は
@AppFunctionServiceEntryPointを付けた抽象クラスにsuspend関数を並べ、KSP にサービスと定義の XML を作らせます。KDoc がエージェント向けの説明になるので英語で書きます。 - App Intents は
AppEntityとEntityStringQueryで対象を表し、AppIntentのperform()で操作し、AppShortcutsProviderで Siri のフレーズを登録します。 - 失敗は、AppFunctions では定義済みの例外に、App Intents では読み上げる文言付きのエラーに直します。候補の名前の一覧も付けます。
- AppFunctions は Gemini から呼べる段階にまだないので、動作は
adb shell cmd app_functionで確かめます。
前提とバージョン
項目 | 内容 |
|---|---|
|
|
AppFunctions が動く端末 | Android 16(API 36)以降 |
ビルドの条件(公式ガイド) |
|
App Intents | iOS 16 以降の API。この例は iOS 18.5 以降、Xcode 26 でビルド |
AppFunctions の公式ドキュメントには「experimental preview」と書かれていて、API は今後変更される(subject to change)と明記されています。Gemini との連携は、2026年5月時点で trusted testers 向けの private preview です。
1.0.0-beta01 では、@AppFunctionDeclaration と @AppFunctionSerializable の isDescribedByKDoc が既定値を持たなくなりました。明示的に書く必要があります。アプリの説明を書く XML の属性も description から instructions に変わっています。
例にするアプリと操作
数値(体重、歩数など)をトラッカーごとに記録するアプリを考えます。外に出す操作は次の4つです。
- トラッカーの一覧と、それぞれの最新の値
- 値の記録
- 1つのトラッカーの最新の値と前回比
- 期間(1週、1ヶ月、3ヶ月、1年、全期間)の平均、最小、最大、件数、変化
共通の設計
操作は共通のコードに置く
計算と書き込みは KMP の共通モジュール(commonMain)にまとめ、App Intents と AppFunctions からはそれを呼ぶだけにします。Android のアプリはこのモジュールを Kotlin のまま使い、iOS のアプリは KMP がビルドした framework を Swift から呼びます。両方の OS で同じ数字を返せて、テストも1か所で済みます。iOS と Android でコードを共有しない場合も、操作の窓口を1つのクラスに集めておくと OS 側が薄くなります。
sealed interface ActionError {
data class NotFound(val query: String, val available: List<String>) : ActionError
data class Ambiguous(val query: String, val candidates: List<String>) : ActionError
data class InvalidValue(val text: String) : ActionError
}
sealed interface Outcome<out T> {
data class Ok<out T>(val value: T) : Outcome<T>
data class Failed(val error: ActionError) : Outcome<Nothing>
}
object TrackerActions {
suspend fun trackers(): List<TrackerInfo> = TODO()
suspend fun search(query: String): List<TrackerInfo> = TODO()
suspend fun latest(tracker: String): Outcome<TrackerInfo> = TODO()
suspend fun summary(tracker: String, range: TimeRange): Outcome<TrackerSummary> = TODO()
suspend fun record(tracker: String, value: String, time: Long?, note: String?): Outcome<RecordedEntry> = TODO()
}失敗は例外ではなく値で返します。どの理由で失敗したかを、OS ごとの形(Android の例外、iOS のエラー文)に直しやすくするためです。
言語に依存しない形で返す
返すのは数値と、単位を付けた文字("72.5 kg"、"+0.3 kg")と、時刻です。文字の数値はアプリの表示言語にかかわらず、桁区切りを「,」、小数点を「.」に固定します。ドイツ語の書式で "5.720" と返すと、エージェントがそれをそのまま渡し返したときに 5.72 と読み違えるためです。
文にするのは OS の側です。Android ではエージェントが自分の言葉で話すので、構造化した値のまま返します。iOS では String Catalog の文に埋めて、Siri のダイアログにします。
名前の揺れは段階的に照らし、曖昧なら止める
Siri もエージェントも、トラッカーを名前で渡してきます。照合は id の完全一致を先に見て、次に名前の完全一致、前方一致、部分一致、編集距離の順に進めます。大文字小文字、全角半角、空白、カタカナとひらがなの違いは無視します。
ある段で2件以上当てはまったら、そこで止めて「曖昧」と返します。勝手に1つを選ぶと、別のトラッカーに記録してしまうためです。編集距離は短い名前には使いません。「体重」と「体温」は1文字しか違わないからです。
Android: AppFunctions
依存関係
plugins {
id("com.google.devtools.ksp")
}
dependencies {
implementation("androidx.appfunctions:appfunctions:1.0.0-rc01")
ksp("androidx.appfunctions:appfunctions-compiler:1.0.0-rc01")
}サービスと関数を宣言する
AppFunctionService を継いだ抽象クラスに @AppFunctionServiceEntryPoint を付けます。KSP が serviceName の名前で具象クラスを作り、appFunctionXmlFileName の名前で関数の定義の XML を作ります。
@RequiresApi(36)
@AppFunctionServiceEntryPoint(
serviceName = "TrackerAppFunctionService",
appFunctionXmlFileName = "tracker_app_function_service",
)
abstract class BaseTrackerAppFunctionService : AppFunctionService() {
/**
* Records a number in one of the user's trackers, such as a body weight of 72.5 in "Weight".
*
* @param tracker The tracker ID from `listTrackers`, or the tracker's name.
* @param value The number to record, such as "72.5" or "5,720". A trailing unit such as "72.5 kg" is allowed.
* @param dateTime Local date and time the value belongs to. Null records it at the current time.
* @param note Short note saved with the entry. Null saves no note.
* @return The saved entry and its difference from the previous value.
*/
@AppFunctionDeclaration(isDescribedByKDoc = true)
suspend fun recordValue(
tracker: String,
value: String,
dateTime: LocalDateTime? = null,
note: String? = null,
): RecordedValue = answer {
val time = dateTime?.atZone(ZoneId.systemDefault())?.toInstant()?.toEpochMilli()
TrackerActions.record(tracker, value, time, note).orThrow().toRecordedValue()
}
}isDescribedByKDoc = trueにすると、KDoc の本文と@param、@returnが関数の説明になります。エージェントが読む文なので英語で書き、値の例や、別の関数の結果を渡せることも書いておきます。- 公式ガイドによると、AppFunction は既定では UI スレッドで動きます。
suspend関数にして、ブロックする処理はDispatchers.IOに切り替えます。 trackerには id と名前のどちらも受けるようにしました。名前で呼べれば、エージェントは先に一覧を取らなくて済みます。
戻り値の型を定義する
戻り値は @AppFunctionSerializable を付けた data class にします。プロパティの KDoc もエージェント向けの説明になります。
/** An entry that was just saved. */
@AppFunctionSerializable(isDescribedByKDoc = true)
data class RecordedValue(
/** ID of the tracker the entry was saved to. */
val trackerId: String,
/** Name of the tracker the entry was saved to. */
val trackerName: String,
/** Saved value as a number. */
val value: Double,
/** Saved value with its unit, always written with "," between thousands and "." as the decimal point, such as "72.5 kg". */
val valueText: String,
/** Local date and time the entry was recorded at. */
val dateTime: LocalDateTime,
/** Difference from the previous value with sign and unit, such as "-0.4 kg". Null when there is no previous value. */
val changeText: String?,
)日付と時刻は java.time の LocalDate と LocalDateTime で渡せます。null になる場合は、いつ null になるかを KDoc に書いておきます。
受け付ける値を絞る
期間のように決まった値しか受けない引数には、@AppFunctionStringValueConstraint で候補を並べます。
@AppFunctionDeclaration(isDescribedByKDoc = true)
suspend fun summarizeTracker(
tracker: String,
@AppFunctionStringValueConstraint(enumValues = ["WEEK", "MONTH", "QUARTER", "YEAR", "ALL"])
range: String? = null,
): TrackerSummary = answer { /* ... */ }エラーを定義済みの例外にする
エージェントに失敗の理由を伝えるには、ライブラリの定義済みの例外を投げます。
失敗 | 投げる例外 |
|---|---|
トラッカーが見つからない |
|
名前が曖昧、値が数値でない、期間が不正 |
|
それ以外 |
|
メッセージには、選び直せるようにトラッカーの名前の一覧を入れます。定義済みの例外以外がそのまま漏れると理由が伝わらないので、関数の本体は共通の関数で包んでいます。
private suspend fun <T> answer(block: suspend () -> T): T =
withContext(Dispatchers.IO) {
try {
block()
} catch (e: AppFunctionException) {
throw e
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
throw AppFunctionAppUnknownException(e.message ?: e.toString())
}
}
private fun <T> Outcome<T>.orThrow(): T =
when (this) {
is Outcome.Ok -> value
is Outcome.Failed -> throw when (val e = error) {
is ActionError.NotFound ->
AppFunctionElementNotFoundException("No tracker matches \"${e.query}\". Trackers: ${e.available.joinToString()}.")
is ActionError.Ambiguous ->
AppFunctionInvalidArgumentException("\"${e.query}\" matches several trackers: ${e.candidates.joinToString()}.")
is ActionError.InvalidValue ->
AppFunctionInvalidArgumentException("\"${e.text}\" is not a number. Pass a value such as \"72.5\".")
}
}Manifest とアプリの説明
KSP が作ったサービスと、アプリ全体の説明を Manifest に書きます。
<service
android:name=".agent.TrackerAppFunctionService"
android:enabled="@bool/app_functions_enabled"
android:exported="true"
android:permission="android.permission.BIND_APP_FUNCTION_SERVICE"
tools:targetApi="36">
<property
android:name="android.app.appfunctions.schema"
android:value="app_functions_schema.xsd" />
<property
android:name="android.app.appfunctions.v2"
android:value="tracker_app_function_service.xml" />
<intent-filter>
<action android:name="android.app.appfunctions.AppFunctionService" />
</intent-filter>
</service>
<property
android:name="android.app.appfunctions.app_metadata"
android:resource="@xml/app_functions_metadata" />app_functions_metadata.xml の instructions には、アプリが何をするかと、関数の使い方の決まりを書きます。
<AppFunctionAppMetadata xmlns:appfn="http://schemas.android.com/apk/androidx.appfunctions"
appfn:instructions="Personal number tracker. The user records numbers such as body weight or steps in trackers.
- Every function that takes 'tracker' accepts the tracker ID or its name.
- The not-found and ambiguous errors list the available tracker names.
- Values are plain numbers in the tracker's unit; there is no unit conversion."
appfn:displayDescription="@string/app_functions_display_description" />Android 15 以前ではサービスを無効にする
minSdk が 36 より低い場合、サービスの android:enabled をリソースで切り替えます。values/bools.xml に false、values-v36/bools.xml に true を置くと、Android 16 以降でだけ有効になります。
<resources>
<bool name="app_functions_enabled">true</bool>
</resources>adb で確かめる
2026年11月時点で、Gemini などのシステムのエージェントから AppFunctions を呼べるのは private preview に参加したアプリだけです。手元の確認は adb shell cmd app_function で行います。Android 16 以降の端末かエミュレーターにアプリを入れてから実行します。
まず、アプリが公開している関数の一覧と定義を出します。
adb shell cmd app_function list-app-functions --package com.example.tracker関数 id の形は <エントリーポイントのクラス名>#<メソッド名> で、KSP が作った具象クラスではなく、@AppFunctionServiceEntryPoint を付けた抽象クラスの名前を使います。引数は JSON で渡します。
adb shell "cmd app_function execute-app-function \
--package com.example.tracker \
--function 'com.example.tracker.agent.BaseTrackerAppFunctionService#recordValue' \
--parameters '{\"tracker\": \"体重\", \"value\": \"72.5\"}'"adb shell の中でさらに引用符を重ねるので、JSON の " は \" にします。確かめておきたいのは次の点です。
- 一覧に4つの関数が出て、KDoc の説明が入っているか
- 名前の表記揺れ(大文字小文字、全角半角、カタカナとひらがな)があっても呼べるか
- 曖昧な名前や数値でない値で、定義済みの例外とメッセージが返るか
- 記録のあと、アプリの画面とウィジェットに値が出ているか
公式ガイドでは、プロンプトなしで動作を確かめられる「AppFunctions testing agent」アプリと、Android Studio の Gemini などに adb shell cmd app_function を使わせて確かめる方法も紹介されています。
iOS: App Intents
AppEntity と EntityStringQuery
Siri やショートカットが指す対象を AppEntity で表します。id はアプリの id をそのまま使います。
struct TrackerEntity: AppEntity {
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "トラッカー")
static let defaultQuery = TrackerQuery()
let id: String
let name: String
let unit: String
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(name)", subtitle: unit.isEmpty ? nil : "\(unit)")
}
}クエリは EntityStringQuery にすると、Siri が聞き取った文字列で探す entities(matching:) を書けます。ここで共通コードの照合を呼べば、Android と同じ規則で名前を照らせます。TrackerActions.shared は、KMP の共通モジュールにある Kotlin の object を Swift から呼ぶときの書き方です。
struct TrackerQuery: EntityStringQuery {
func entities(for identifiers: [String]) async throws -> [TrackerEntity] {
let all = try await TrackerActions.shared.trackers()
return identifiers.compactMap { id in all.first { $0.id == id }.map(TrackerEntity.init) }
}
func entities(matching string: String) async throws -> [TrackerEntity] {
try await TrackerActions.shared.search(query: string).map(TrackerEntity.init)
}
func suggestedEntities() async throws -> [TrackerEntity] {
try await TrackerActions.shared.trackers().map(TrackerEntity.init)
}
}AppIntent
引数は @Parameter で宣言し、perform() で共通コードを呼びます。戻り値に ProvidesDialog を付けると Siri が読み上げる文を、ShowsSnippetView を付けると結果に出す小さな SwiftUI のビューを返せます。
struct RecordValueIntent: AppIntent {
static let title: LocalizedStringResource = "値を記録"
static let description = IntentDescription("トラッカーに数値を記録します。日時を省くと今の時刻で記録します。")
@Parameter(title: "トラッカー")
var tracker: TrackerEntity
@Parameter(title: "値")
var value: Double
@Parameter(title: "日時")
var date: Date?
@Parameter(title: "メモ")
var note: String?
@MainActor
func perform() async throws -> some IntentResult & ProvidesDialog & ShowsSnippetView {
let saved = try await TrackerActions.shared.record(tracker: tracker.id, value: "\(value)", time: date?.epochMillis, note: note).unwrap()
let dialog: LocalizedStringResource = "\(saved.trackerName)に \(saved.valueText) を記録しました。"
return .result(dialog: IntentDialog(dialog), view: ReadingSnippet(saved))
}
}必須の @Parameter が足りないときは、システムが聞き返します。フレーズにはトラッカーだけを入れ、値はあとから聞き返す形にしました。
AppEnum で選択肢を受ける
期間のような選択肢は AppEnum にします。@Parameter に default: を付けると省略できます。
enum SummaryRange: String, AppEnum {
case week, month, quarter, year, all
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "期間")
static let caseDisplayRepresentations: [SummaryRange: DisplayRepresentation] = [
.week: "1週", .month: "1ヶ月", .quarter: "3ヶ月", .year: "1年", .all: "全期間",
]
}
struct GetSummaryIntent: AppIntent {
static let title: LocalizedStringResource = "期間のまとめを見る"
@Parameter(title: "トラッカー")
var tracker: TrackerEntity
@Parameter(title: "期間", default: .month)
var range: SummaryRange
func perform() async throws -> some IntentResult & ProvidesDialog { /* ... */ }
}読み上げる文言付きのエラー
perform() から投げるエラーを CustomLocalizedStringResourceConvertible にすると、その文言を Siri が読み上げます。Android と同じく、候補の名前を入れます。
enum ActionFailure: Error, CustomLocalizedStringResourceConvertible {
case notFound(query: String, available: [String])
case ambiguous(query: String, candidates: [String])
case invalidValue(String)
var localizedStringResource: LocalizedStringResource {
switch self {
case let .notFound(query, available):
"「\(query)」というトラッカーはありません。あるのは \(available.formatted(.list(type: .and))) です。"
case let .ambiguous(query, candidates):
"「\(query)」に当てはまるトラッカーが複数あります:\(candidates.formatted(.list(type: .or)))"
case let .invalidValue(text):
"「\(text)」は数値ではありません。"
}
}
}AppShortcutsProvider で Siri のフレーズを登録する
AppShortcutsProvider に並べた intent は、設定なしで Siri、ショートカット、Spotlight に出ます。フレーズには .applicationName が必須で、AppEntity の引数も埋め込めます。
struct TrackerShortcuts: AppShortcutsProvider {
static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: RecordValueIntent(),
phrases: [
"\(.applicationName)で\(\.$tracker)を記録",
"\(.applicationName)で記録",
],
shortTitle: "値を記録",
systemImageName: "plus.circle"
)
}
}フレーズに入れたトラッカーの候補は、Siri が事前に覚えます。トラッカーを足したり名前を変えたりしたら TrackerShortcuts.updateAppShortcutParameters() を呼んで、候補を作り直させます。
画面なしで起動されたときの初期化
openAppWhenRun の既定は false で、このときシステムはアプリを前に出さずに intent を実行します。画面は作られないので、DB を開くなどの初期化を画面の側に置いていると動きません。初期化を1つの関数にまとめ、App の init と、各 intent とクエリの最初から呼ぶようにします。2回目以降は何もしない作りにします。
なお iOS 26 の SDK では openAppWhenRun が非推奨になり、代わりに supportedModes を使うよう案内されています(2026-11-07 確認)。
応答のあとに止められる前提で書く
Siri やエージェントに応答を返したあと、アプリのプロセスはすぐ止められることがあります。データの変更を購読して少し待ってからウィジェットを描き直す作りだと、描き直す前に止まって古い値が残ります。記録する操作では、応答を返す前にウィジェットを更新します。
- Android: Glance なら
updateAll(context)を呼んでから戻り値を返す - iOS: ウィジェットが読むファイルを書き、
WidgetCenter.shared.reloadAllTimelines()を呼んでから.resultを返す
KMP の共通コードを App Intents から呼ぶときの注意
KMP の共通モジュールを framework にして、App Intents の Swift から呼ぶときの注意です。
- Swift から呼ぶ
suspend関数には@Throws(Exception::class)を付けます。付けないと、Kotlin の例外が Swift に届いたときにプロセスごと落ちます。 - Kotlin のジェネリクスは Objective-C を経由すると型引数が消えます。
Outcome<T>は Swift 側でOutcome.Okにキャストし、取り出す側で型を決めます。 - App Intents はアプリのターゲットに置きます。ウィジェットの拡張に framework を入れていない場合、拡張からは共通コードを呼べません。
対応表
項目 | AppFunctions(Android) | App Intents(iOS) |
|---|---|---|
宣言 |
|
|
生成 | KSP がサービスと定義の XML を作る | Xcode のビルドがメタデータを作る |
説明文 | KDoc(英語、エージェントが読む) |
|
引数 | 関数の引数( |
|
選択肢 |
|
|
操作の対象 | id か名前の文字列 |
|
戻り値 |
|
|
文にするのは | エージェント | アプリ(String Catalog の文) |
エラー |
|
|
アプリ全体の説明 |
| なし(フレーズは |
呼び出し元 | 権限を持つエージェント(Gemini は private preview) | Siri、ショートカット、Spotlight |
対応 OS | Android 16(API 36)以降 | iOS 16 以降 |
手元での確認 |
| ショートカットアプリ、Siri |
公開情報がない項目
- AppFunctions の Gemini 連携が一般のアプリに開放される時期: 公式ドキュメントに記載なし(2026-11-07 確認)
execute-app-functionの--parametersでLocalDateTimeを渡すときの JSON の形: 公式ドキュメントに記載なし(2026-11-07 確認)