/shiny:shiny-appfunctionsfrom shiny
Guide for exposing a .NET MAUI / .NET app's functions to Siri, Spotlight, Shortcuts and Apple Intelligence (App Intents) and to Gemini and other agents (Android AppFunctions) from one C# declaration using Shiny.AppFunctions - [AppFunction] records, typed handlers, [AppEntity] entities with queries, [AppShortcut] Siri phrases and delegates
Ships in shiny. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Use this skill when the user needs to:
IChatClient) the same functions as tools - Shiny.AppFunctions.Extensions.AI| Item | Value |
|---|---|
| NuGet | Shiny.AppFunctions (the source generator and the MSBuild task ship inside it); optional Shiny.AppFunctions.Extensions.AI for LLM tools |
| Namespace | Shiny.AppFunctions |
| Registration | services.AddAppFunctions() - source-generated into the app, in Microsoft.Extensions.DependencyInjection |
| Host | Shiny.Core (.UseShiny() on MAUI) - no MAUI dependency |
| Platforms | iOS 16+ (App Intents), Android 16 / API 36+ (AppFunctions; a no-op below). net10.0 carries the contracts and the dispatcher - no platform bridge. No Mac Catalyst/macOS/Windows bridge |
The user writes no Swift, Kotlin, Info.plist, entitlements or AndroidManifest entries. The generator writes the DI registration, binding, dispatch, the Swift App Intents and the Android schema; the package's build targets compile the Swift into the iOS app (and run Apple's metadata + Siri phrase processors) and add the schema assets on Android. The Android service arrives through the manifest merger.
// MauiProgram.cs
builder
.UseMauiApp<App>()
.UseShiny(); // required - the runtime starts from a Shiny startup task
builder.Services.AddAppFunctions(); // generated: every handler, entity query and delegate in this project
OutputType=Exe / the Android application). The generator only scans the project it runs in - [AppFunction] records, handlers, [AppEntity] records, IAppEntityQuery<T> and IAppFunctionDelegate classes in a class library are not found. Services, enums and result records used by them may come from any library.[AppFunction("id")] implementing IAppFunction (no result) or IAppFunction<TResult> - exactly one of them.create_order). Shared by both platforms; changing one breaks saved Shortcuts and agent references.IAppFunctionHandler<TRequest> or IAppFunctionHandler<TRequest, TResult>, a public non-abstract class with a public constructor. Resolved from a new DI scope per call - scoped services are fine.init properties are optional unless C# required (a value not sent keeps the property default);Description - assistants decide when to call a function from it.using Shiny.AppFunctions;
public enum Priority { Low, Normal, Urgent } // → Swift AppEnum / Android enumValues
[AppEntity("customer", Title = "Customer")] // needs a public string Id
public record Customer(string Id, string Name, string City); // display: DisplayProperty, else Name, Title, Id
public class CustomerQuery(ICustomers customers) : IAppEntityQuery<Customer>
{
public Task<IReadOnlyList<Customer>> GetByIds(IReadOnlyList<string> ids, CancellationToken ct) => customers.ByIds(ids, ct);
public Task<IReadOnlyList<Customer>> Search(string text, CancellationToken ct) => customers.Search(text, ct);
public Task<IReadOnlyList<Customer>> Suggested(CancellationToken ct) => customers.Recent(ct); // optional (default: empty)
}
public record OrderResult(string Number, int Quantity, double Total);
[AppFunction("create_order", Description = "Creates an order for a customer")]
[AppShortcut("Create an order in ${applicationName}", ShortTitle = "New Order", SystemImage = "cart.badge.plus")]
public record CreateOrder(
[property: AppParameter(Title = "Customer", Description = "Who the order is for")] Customer Customer,
int Quantity,
Priority Priority,
string? Note // nullable → optional
) : IAppFunction<OrderResult>;
public class CreateOrderHandler(IOrders orders) : IAppFunctionHandler<CreateOrder, OrderResult>
{
public async Task<OrderResult> Handle(CreateOrder request, AppFunctionContext context, CancellationToken ct)
{
if (request.Quantity < 1)
throw new AppFunctionException(AppFunctionErrorCode.InvalidArgument, "Quantity must be at least 1"); // message is shown/spoken
var order = await orders.Create(request.Customer.Id, request.Quantity, request.Priority, request.Note, ct);
context.Say($"Order {order.Number} is in."); // Siri dialog; Android returns it in the response extras
return new OrderResult(order.Number, order.Quantity, order.Total);
}
}
[AppFunction("count_open_orders", Title = "Open Orders", Description = "Counts the orders that have not shipped")]
[AppShortcut("How many orders are open in ${applicationName}", SystemImage = "shippingbox")]
public record CountOpenOrders : IAppFunction<int>;
| Parameters | Results | |
|---|---|---|
string, int, long, double, bool, DateTimeOffset | ✅ (nullable = optional) | ✅ |
| enums (wire value = member name) | ✅ | ✅ |
[AppEntity] records | ✅ (id on the wire, resolved through IAppEntityQuery<T>; unknown id → NotFound) | as plain objects |
| records / classes of the above | ❌ | ✅ (nested up to 4 levels) |
| arrays / lists | ❌ | ✅ |
| no result | IAppFunction + IAppFunctionHandler<TRequest> |
No Guid, DateTime, decimal, float, collections or nested objects as parameters - use string / double / DateTimeOffset or an entity.
iOS: a primitive result is returned typed; an object or list result is returned as JSON text, and the dialog is whatever context.Say(...) set.
[AppEntity] needs an IAppEntityQuery<T> in the app project (SHAF009 otherwise).Suggested before typing, Search while typing, GetByIds to rehydrate).search_{id} function (returns [{id, title}]) that agents call to find ids.[AppShortcut("phrase")] - every phrase must contain ${applicationName} (SHAF011). Repeat the attribute for more phrases; the first one's ShortTitle / SystemImage (an SF Symbol) are used.CFBundleDevelopmentRegion is added to the built Info.plist (default en) when missing, because Siri phrase training needs it.public class SignInDelegate(IAuth auth) : IAppFunctionDelegate
{
public Task<AppFunctionGate> OnInvoking(AppFunctionContext context, CancellationToken ct)
=> Task.FromResult(context.FunctionId != "cancel_order" || auth.IsSignedIn
? AppFunctionGate.Allow
: context.IsForeground
? AppFunctionGate.Deny("Sign in to cancel orders.") // already in the app - OpenApp would pass
: AppFunctionGate.OpenApp("Sign in to cancel orders."));
}
public class TelemetryDelegate(ILogger<TelemetryDelegate> logger) : IAppFunctionDelegate
{
public Task OnInvoked(AppFunctionContext context, object? result, Exception? exception)
{
logger.LogInformation("{Fn} from {Platform}: {Outcome}", context.FunctionId, context.Platform, exception?.Message ?? "ok");
return Task.CompletedTask;
}
}
AddAppFunctions() registers them; the first OnInvoking that does not return Allow wins. Don't make one delegate depend on another having run first.AppFunctionGate.Deny(message) refuses (Denied). AppFunctionGate.OpenApp(message): iOS asks the user to continue in the app, then runs the call again in the foreground (context.IsForeground == true); Android refuses with the message. Anything already foreground passes an OpenApp gate - including a call made while the user is in the app (Siri/Gemini over it, or an in-app AI chat), on both platforms. OpenApp means "needs the app on screen", not "needs sign-in": for a state check, return OpenApp only when !context.IsForeground and Deny otherwise (as above), or a foreground call runs signed out.OnInvoked as AppFunctionException(Denied, message). Exceptions thrown from OnInvoked are logged and ignored.AppFunctionContext: FunctionId, Function (descriptor), Platform (Apple/Android/Other), IsForeground, CallerPackage (Android caller), Request, Services (the call's scope), Items (shared with the handler), Say(dialog) / Dialog.[AppFunction(OpensApp = true)] = the function needs the app on screen (UI work, navigation) - a built-in OpenApp gate checked before any delegate. iOS brings the app to the foreground before the handler runs; Android (which cannot bring an app forward from the background) runs it only while the app is visible and otherwise refuses it (Denied, "Open the app to continue"); direct AppFunctionDispatcher calls that aren't foreground are refused the same way. Prefer it over writing a delegate for "foreground only".context.IsForeground is true when the app is on screen: the user asked Siri/Gemini from inside the app (iOS: any state but background; Android: any started activity), the call came from the in-app AI tools, or iOS foregrounded it. The handler runs in the app's own process and container, so it may navigate or update view models - but only after checking IsForeground, and on the main thread (MainThread.InvokeOnMainThreadAsync); handlers never run on it.Throw AppFunctionException(code, message) - write the message for the user. Any other exception becomes AppError.
AppFunctionErrorCode | Android AppFunctionError | Use for |
|---|---|---|
InvalidArgument | InvalidArgument | bad / missing input (binding throws this itself for missing required values) |
NotFound | InvalidArgument (unknown entity) / FunctionNotFound (unknown function) | the thing asked about doesn't exist |
Denied | Denied | not allowed |
Cancelled | Cancelled | caller cancelled / OS time budget ran out |
AppError | AppUnknownError | anything else |
On iOS the message becomes the Siri error dialog.
The same pipeline Siri and Gemini use (new scope → bind → delegates → handler → JSON result). It never throws.
public class MyViewModel(AppFunctionDispatcher dispatcher)
{
async Task Run()
{
var outcome = await dispatcher.Execute(
new AppFunctionInvocation("create_order"), // Platform = Other, IsForeground = false
"""{"customer":"acme","quantity":2,"priority":"Normal"}""",
CancellationToken.None
);
// outcome.Status (Success/Error/NeedsForeground), ResultJson, Dialog, ErrorCode, Message
}
}
dispatcher.Registry.Functions lists every function (declared ones, then the generated search_*), each with GetParametersJsonSchema() (JSON schema draft 2020-12) - the hook for an MCP adapter.
The optional Shiny.AppFunctions.Extensions.AI package hands the same functions to an in-app LLM as Microsoft.Extensions.AI tools (AIFunctions). Don't hand-write AIFunctions for app functions - use this.
builder.Services.AddAppFunctions(); // generated - required
builder.Services.AddAppFunctionAITools(b => b
.AddAllFunctions() // or .AddFunction("create_order")
.ExcludeFunction("cancel_order") // optional
);
// resolve the bundle and pass the tools to any IChatClient - combine freely with the other Shiny AI tool bundles
var tools = sp.GetRequiredService<AppFunctionAITools>().Tools
.Concat(sp.GetRequiredService<CalendarAITools>().Tools)
.ToList();
var response = await chatClient.GetResponseAsync(messages, new ChatOptions { Tools = tools });
AddAppFunctionAITools(Action<IAppFunctionAIToolBuilder>) (namespace Shiny) - throws at registration if nothing was added. Ids are checked when AppFunctionAITools is first resolved; an unknown id throws.IAppFunctionAIToolBuilder - AddAllFunctions(), AddFunction(id), AddFunctions(ids), ExcludeFunction(id). A function with an [AppEntity] parameter brings its search_{entity} tool along so the model can find ids; ExcludeFunction wins over both.AppFunctionAITools - resolve from DI (singleton); .Tools is IReadOnlyList<AITool>, in registry order.Description, schema = GetParametersJsonSchema() (entity parameters are described as ids found with search_{entity}).AppFunctionDispatcher.Execute with AppFunctionPlatform.Other and IsForeground = true (the chat is running in the app): same binding, same delegates, same handler. OpensApp functions run and OpenApp gates pass; a sign-in check must Deny when IsForeground (see Delegates) or the model can call the function signed out. Check context.Platform == AppFunctionPlatform.Other in a delegate to treat AI calls differently.{ "success": true, "result": <function result>, "message": "<context.Say text>" } (result omitted for IAppFunction, message when not set); failure → { "error": "<message>", "code": "InvalidArgument|NotFound|Denied|Cancelled|AppError" }. Nothing throws to the chat client.JsonNodes.Related AI tool packages (same *AITools bundle pattern, see their skills): Shiny.Calendar.Extensions.AI (shiny-calendarstore), Shiny.Contacts.Extensions.AI (shiny-contactstore), Shiny.Notifications.Extensions.AI (shiny-notifications), Shiny.Locations.Extensions.AI (shiny-locations).
| Property | Default | |
|---|---|---|
ShinyAppFunctionsEnabled | true | false skips Swift/metadata/assets generation |
ShinyAppFunctionsMinimumOSVersion | app's SupportedOSPlatformVersion, at least 16.0 | iOS deployment target of the Swift intents |
ShinyAppFunctionsDevelopmentRegion | en | added to Info.plist only if it has no CFBundleDevelopmentRegion |
ShinyAppFunctionsConstProtocolsFile | the Xcode 27 list shipped in the package | swiftc const-extraction protocol list; override for a later Xcode |
The iOS Swift/metadata steps run only on a macOS build host. A Windows build with no paired Mac skips them; a Windows build paired to a Mac fails with a Shiny.AppFunctions error - build on the Mac, or set ShinyAppFunctionsEnabled=false for those builds. Never suggest a ShinyAppFunctionsEnabled workaround for plain Windows builds; none is needed.
| Id | Meaning |
|---|---|
| SHAF001 | invalid function/entity id |
| SHAF002 | [AppFunction] type implements neither/both of IAppFunction, IAppFunction<T> |
| SHAF003 | unsupported parameter/result type |
| SHAF004 | request can't be constructed (no matching public constructor / settable properties) |
| SHAF005 / SHAF006 | no handler / more than one handler |
| SHAF007 / SHAF008 | entity has no public string Id / display property not found |
| SHAF009 | entity has no IAppEntityQuery<T> |
| SHAF010 | duplicate id |
| SHAF011 | App Shortcut phrase without ${applicationName} |
| SHAF012 | more than 10 App Shortcuts |
| SHAF013 | handler/query/delegate has no public constructor |
# Android 16+ emulator/device - every call can be a cold start
adb shell cmd app_function list-app-functions --package <applicationId>
adb shell "cmd app_function execute-app-function --package <applicationId> --function create_order --parameters '{\"customer\":\"acme\",\"quantity\":2,\"priority\":\"Normal\"}'"
ShortTitle / phrase in Spotlight, or use the Shortcuts app.adb install must set <EmbedAssembliesIntoApk>true</EmbedAssembliesIntoApk> - the system starts the process without Fast Deployment's files. dotnet build -t:Run / -t:Install is fine.AppFunctionDispatcher.CancellationToken.context.Say(...) and AppFunctionException messages.AddAppFunctions() does it (handlers and queries scoped, delegates scoped via TryAddEnumerable); a second registration with another lifetime runs a delegate twice.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub shinyorg/skills --plugin shiny57 skills in this plugin
/localizegenGenerate strongly-typed localization classes from .resx resource files using Shiny.Extensions.Localization.Generator for .NET applications/shiny-accessorysetupGenerate code using Shiny.BluetoothLE.AccessorySetup - the system accessory pairing sheet for BLE devices (AccessorySetupKit on iOS 18+, CompanionDeviceManager on Android) with no MFi, no location prompt and no general Bluetooth prompt on iOS; picked accessories open as Shiny.BluetoothLE peripherals, and Android adds background presence (device appeared / disappeared) events/shiny-actorsGenerate code using Shiny.Actors — Orleans-style virtual actors without the ceremony, AOT/trim-clean, running anywhere .NET runs including .NET MAUI and Blazor WebAssembly. Covers actor interfaces and source-generated proxies, the ShinyActorBuilder (AddShinyActors), persistent state with ETags, named states and auto-save, event-sourced JournaledActor with snapshots, state and event migrations, typed streams (durable, implicit consumers), timers and persistent reminders (background jobs via Shiny.Jobs, on-time OS notifications via Shiny.Notifications), concurrency control ([Reentrant], [AlwaysInterleave], [ReadOnly], [StatelessWorker]), call filters and request context, OpenTelemetry traces and metrics, remoting over HTTP (Shiny.Net.HttpServer server, RemoteActorSystem client), mDNS discovery of actor servers, Shiny.DocumentDb storage (SQLite, PostgreSQL, IndexedDB...), and the ActorTestHost testing kit.Other plugins' skills for the same job