add-geolocation — скилл для Claude Code: что делает и как установить
Скилл add-geolocation помогает добавить в мобильное приложение фоновое GPS-отслеживание с сохранением данных и отправкой в Dataverse. Его вызывает команда /add-native geolocation.
MIT ★ 1 167 обновлён 2026-10-29
/plugin marketplace add microsoft/power-platform-skills
/plugin install mobile-app@power-platform-skillsЧто делает add-geolocation
Скилл проверяет, что проект уже содержит пакет @microsoft/power-apps-native-bglocation, а в Dataverse есть таблица msdyn_locationrecords и нужные столбцы. Затем он создаёт или обновляет src/native/geolocation.ts, где используются geoService и BgLocationClient. Экраны должны обращаться к этой обёртке, а не к пакету напрямую.
Отслеживание рассчитано на работу в фоне: конфигурация требует trackInBackground и persistAcrossRestarts. Для авторизации используется MSAL, а целевая таблица и сопоставленные поля должны пройти проверку. Если таблицы или столбцов не хватает, скилл останавливается; установить пакет или менять нативную конфигурацию он не должен. Для чтения координат только на переднем плане предусмотрена другая команда — /add-native location.
Какие задачи решает
- добавить фоновое GPS-отслеживание в мобильное приложение
- сохранять координаты после перезапуска приложения
- отправлять данные геолокации в Dataverse
- проверить таблицу и столбцы для записи координат
Примеры запросов агенту
- Добавь в приложение фоновое отслеживание GPS через
/add-native geolocation. - Настрой запись фоновых координат в Dataverse командой
/add-native location-tracking. - Подключи
@microsoft/power-apps-native-bglocationдля фонового отслеживания через/add-native background-location.
Как установить add-geolocation
1Через маркетплейс плагинов
/plugin marketplace add microsoft/power-platform-skills/plugin install mobile-app@power-platform-skillsКоманда ставит плагин mobile-app целиком, со всеми его скиллами
2Через Skills CLI (Vercel)
npx skills add microsoft/power-platform-skills --skill add-geolocation -a claude-code3Вручную: положить файлы
~/.claude/skills/add-geolocation/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/add-geolocation/
1Через Skills CLI (Vercel)
npx skills add microsoft/power-platform-skills --skill add-geolocation -a codex2Вручную: положить файлы
.agents/skills/add-geolocation/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add microsoft/power-platform-skills --skill add-geolocation -a cursor2Вручную: положить файлы
.cursor/skills/add-geolocation/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install microsoft/power-platform-skills plugins/mobile-apps/skills/add-native/add-geolocation2Вручную: положить файлы
.github/skills/add-geolocation/SKILL.md1Через Skills CLI (Vercel)
npx skills add microsoft/power-platform-skills --skill add-geolocation -a gemini-cli2Командой платформы
gemini skills install https://github.com/microsoft/power-platform-skills --path plugins/mobile-apps/skills/add-native/add-geolocationВручную: положить файлы
.devin/skills/add-geolocation/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Claude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы об add-geolocation
Как установить add-geolocation в Claude Code?
Добавьте маркетплейс командой /plugin marketplace add microsoft/power-platform-skills, затем установите плагин командой /plugin install mobile-app@power-platform-skills.
Что делает add-geolocation?
Скилл настраивает фоновое GPS-отслеживание с долговременным хранением и синхронизацией с Dataverse. Его вызывает /add-native.
Какие условия нужны для записи координат в Dataverse?
В проекте уже должен быть пакет @microsoft/power-apps-native-bglocation, а в Dataverse — таблица msdyn_locationrecords с нужными столбцами. Скилл проверяет их до изменения обёртки src/native/geolocation.ts.
Исходный текст
SKILL.md · MIT
---
name: add-geolocation
description: Internal implementation skill invoked by /add-native for native background GPS tracking with durable storage and Dataverse sync using @microsoft/power-apps-native-bglocation.
user-invocable: false
disable-model-invocation: true
allowed-tools: Read, Edit, Write, Grep, Glob, Bash, AskUserQuestion
model: sonnet
---
**Shared instructions: [shared-instructions.md](${PLUGIN_ROOT}/shared/shared-instructions.md)** - read first.
**Working directory:** before any project read or command, execute
[native-artifact-compatibility.md Step 0](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md#0-bind-every-operation-to-the-app-root).
Inherit `/add-native`'s resolved absolute `working_dir`; bind every shell call and
file tool to it, even when this helper starts from another directory.
# Add Geolocation
Internal helper for `/add-native geolocation`, `/add-native location-tracking`, `/add-native background-location`, `/add-native gps-tracking`, and `/add-native @microsoft/power-apps-native-bglocation`.
Use this only for continuous/background GPS tracking with native durable storage and inline Dataverse upload. For a single foreground coordinate read, use `/add-native location` (`expo-location`) instead.
Hard rules:
- Auth is MSAL-only. Do not expose OneAuth or an auth selector.
- Use `geoService(dataSource, app_id)` and `BgLocationClient`.
- Do not use `GeolocationExtension`, HostingSDK, PCF, Launch URI, or CordovaV2 bridge paths.
- Do not install packages or edit native config.
- The control is not usable until its Dataverse target table and mapped columns are verified.
## 1. Verify app and package
```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
test -f app.config.js && test -f power.config.json && test -f package.json && test -d src || { echo "BLOCKED: working_dir is not an initialized app" >&2; exit 1; }
node -e "const p=require('./package.json'); const m='@microsoft/power-apps-native-bglocation'; if (!p.dependencies?.[m]) { console.error('MISSING: ' + m); process.exit(1); } console.log('OK: geolocation package present');"
```
If either check fails, stop. The template/app must already ship the native package.
## 2. Verify the Dataverse target table first
This control uses the package default Dataverse entity set:
```text
msdyn_locationrecords
```
Do not ask the user for a table name and do not invent a custom table. `msdyn_locationrecords` must already exist before the control can be used.
```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
ENV_JSON=$(node "${PLUGIN_ROOT}/scripts/resolve-environment.js" "$(node -e "console.log(require('./power.config.json').environmentId)")")
ENV_URL=$(node -e "const j=JSON.parse(process.argv[1]); process.stdout.write(j.environmentUrl || '')" "$ENV_JSON")
TABLE="msdyn_locationrecords"
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "$ENV_URL" GET \
"EntityDefinitions?\$filter=EntitySetName eq '$TABLE'&\$select=LogicalName,EntitySetName"
```
Required result:
- One row returned: capture `LogicalName` and verify columns.
- Empty `value: []`: stop. Mark `BLOCKED (target table missing)`. Do not create the table, do not route to `/add-dataverse`, and do not report the control as usable. Tell the user to run the geolocation-control table provisioning/setup mechanism, then re-run `/add-native geolocation`.
- Auth/environment error: stop. Mark `UNVERIFIED (target table not checked)`. Do not report the control as usable.
When the table exists, verify every mapped column exists:
```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "$ENV_URL" GET \
"EntityDefinitions(LogicalName='<logicalName>')/Attributes?\$select=LogicalName,AttributeType"
```
Required default `fieldMap` columns from the package README:
```text
msdyn_locationrecordid, msdyn_appid, msdyn_latitude, msdyn_longitude,
msdyn_altitude, msdyn_accuracy, msdyn_heading, msdyn_speed, msdyn_timestamp
```
If any active `fieldMap` column is missing, stop. Mark `BLOCKED (target columns missing)` and tell the user to fix the control table through the geolocation-control table provisioning/setup mechanism.
## 2a. Reconcile requested artifacts
Read and execute [native-artifact-compatibility.md](${PLUGIN_ROOT}/shared/references/native-artifact-compatibility.md)
Steps 1–3 for the geolocation row before any writes or reuse. Inherit the current
approval/mode from `/add-native`; do not repeat a valid scoped approval.
Inspect `src/native/geolocation.ts` for all requested tracking/status/location
exports, `GeoTrackingTarget`, MSAL-only `geoService`/`BgLocationClient`, required
`connectionUrl`/`trackInBackground`/`persistAcrossRestarts`, durable storage, and
Dataverse sync. Reuse Step 2's verified `msdyn_locationrecords` columns; one-shot
location or a wrapper targeting another table is not compatible. An incompatible
artifact outside approval returns `NEEDS_CONTEXT` to the owner, or asks standalone;
missing table/columns remain `BLOCKED`, never a usable-control success.
## 3. Write `src/native/geolocation.ts`
Apply Step 2a's decision for `src/native/geolocation.ts`: create when requested
and missing, reuse unchanged only if compatible, or make only the approved scoped
update. Preserve custom code, exports, and callers; do not overwrite from the
example. Screens import this wrapper, not the package directly.
The target config must require the README's two tracking flags:
- `trackInBackground: boolean`
- `persistAcrossRestarts: boolean`
```ts
// src/native/geolocation.ts
import {
geoService,
BgLocationClient,
AuthMethod,
ConnectionType,
} from '@microsoft/power-apps-native-bglocation';
import type {
DataverseDataSource,
LocationData,
PermissionStatus,
} from '@microsoft/power-apps-native-bglocation';
export type { LocationData, PermissionStatus } from '@microsoft/power-apps-native-bglocation';
export type GeoTrackingTarget = Omit<DataverseDataSource, 'authMethod' | 'connectionType'>;
export type GeoResult<T> =
| { ok: true; value: T }
| {
ok: false;
reason: 'NATIVE_MODULE_MISSING' | 'PERMISSION_DENIED' | 'TRACKING_FAILED';
message?: string;
};
let activeClient: BgLocationClient | null = null;
function client(): BgLocationClient {
return activeClient ?? new BgLocationClient();
}
function dataSource(target: GeoTrackingTarget): DataverseDataSource {
return {
...target,
authMethod: AuthMethod.MSAL,
connectionType: ConnectionType.Dataverse,
};
}
function fail(error: unknown): Extract<GeoResult<never>, { ok: false }> {
const message = error instanceof Error ? error.message : String(error);
if (/native|module|not.*link|undefined is not an object|null is not an object/i.test(message)) {
return { ok: false, reason: 'NATIVE_MODULE_MISSING', message };
}
if (/permission|denied|authoriz|not granted/i.test(message)) {
return { ok: false, reason: 'PERMISSION_DENIED', message };
}
return { ok: false, reason: 'TRACKING_FAILED', message };
}
export async function startTracking(
app_id: string,
target: GeoTrackingTarget,
): Promise<GeoResult<void>> {
try {
activeClient = geoService(dataSource(target), app_id);
await activeClient.startTracking();
return { ok: true, value: undefined };
} catch (error) {
activeClient = null;
return fail(error);
}
}
export async function stopTracking(): Promise<GeoResult<void>> {
try {
await client().stopTracking();
activeClient = null;
return { ok: true, value: undefined };
} catch (error) {
return fail(error);
}
}
export async function isTracking(): Promise<GeoResult<boolean>> {
try {
return { ok: true, value: await client().isTracking() };
} catch (error) {
return fail(error);
}
}
export async function getPermissionStatus(): Promise<GeoResult<PermissionStatus>> {
try {
return { ok: true, value: await client().getPermissionStatus() };
} catch (error) {
return fail(error);
}
}
export async function getCurrentLocation(): Promise<GeoResult<LocationData>> {
try {
return { ok: true, value: await client().getCurrentLocation() };
} catch (error) {
return fail(error);
}
}
```
## 4. Usage shape
Integration guidance for the owner; do not edit screens in this helper.
Screens must pass `connectionUrl`, `trackInBackground`, and `persistAcrossRestarts`. Do not pass `tableName` or `fieldMap`; the control uses the default `msdyn_locationrecords` table and default `msdyn_*` field map. `intervalMs`, `distanceFilterMeters`, and `notification` are optional.
```ts
const target: GeoTrackingTarget = {
connectionUrl: 'https://org.crm.dynamics.com',
trackInBackground: true,
persistAcrossRestarts: false,
};
await startTracking('my-wrap-app', target);
```
## 5. Type-check and summary
```bash
cd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }
npx --no-install tsc --noEmit
```
Execute the shared compatibility contract's Step 4 after type-checking. Recheck
all requested tracking APIs/flags, MSAL auth, durable storage/sync, and failure
paths. Type-check success alone is insufficient; do not fix screen/generated
files. Only after the requested artifact contract, table + columns, and
TypeScript all pass, return the shared compatibility result and actual
created/updated/reused paths before reporting:
```text
Geolocation status : READY
Package present : @microsoft/power-apps-native-bglocation
Wrapper : src/native/geolocation.ts
Required config : connectionUrl, trackInBackground, persistAcrossRestarts
Auth : MSAL only
Target table : <TABLE> verified
Native config : not changed
```
If table verification failed, report `BLOCKED` or `UNVERIFIED` instead and do not update `memory-bank.md` as if the control is ready.
© Microsoft · MIT · microsoft/power-platform-skills