← CrowdStrike Falcon FoundryCONTENT HISTORY
WHAT CHANGED
changed
Update to CrowdStrike Falcon Foundry
Snapshot Nov 12, 2026 · 18:46 UTC · version 1.7.1
Collection source: downloaded plugin package.
Instructions updated for functions-falcon-api
Skill instructions — Now says: version: 1.7.1 updated: 2026-11-10
Observed in instructions or declared skills. Runtime behavior has not been tested.
Save CrowdStrike Falcon Foundry and check future changes in Following.
Up to 3 plugins free · no card required.
All fields and original values.
Skill instructions
Before
Nov 4, 2026 · 12:08 UTC
version: 1.7.0 updated: 2026-10-30
After
Nov 12, 2026 · 18:46 UTC
version: 1.7.1 updated: 2026-11-10
Compare saved observations
Download comparison JSONSKILL.md text changes
− removed · + added
--- before +++ after @@ -1,8 +1,8 @@ --- name: functions-falcon-api description: Call CrowdStrike Falcon platform APIs (detections, alerts, hosts, RTR) from within Foundry function handlers. TRIGGER when user asks to "call Falcon APIs from a function", "use FalconPy in a function", "use gofalcon in a function", or needs to integrate Falcon platform APIs within serverless function code. DO NOT TRIGGER when user wants to expose external third-party APIs to Foundry — use api-integrations instead. -version: 1.7.0 -updated: 2026-10-30 +version: 1.7.1 +updated: 2026-11-10 tags: [foundry, functions, falcon-api, falconpy, gofalcon] author: CrowdStrike license: MIT
Full technical diff · 1 changed fields
changed /skill_md_contents
BEFORE
"---\nname: functions-falcon-api\ndescription: Call CrowdStrike Falcon platform APIs (detections, alerts, hosts, RTR) from within Foundry function handlers. TRIGGER when user asks to \"call Falcon APIs from a function\", \"use FalconPy in a function\", \"use gofalcon in a function\", or needs to integrate Falcon platform APIs within serverless function code. DO NOT TRIGGER when user wants to expose external third-party APIs to Foundry — use api-integrations instead.\nversion: 1.7.0\nupdated: 2026-10-30\ntags: [foundry, functions, falcon-api, falconpy, gofalcon]\nauthor: CrowdStrike\nlicense: MIT\ncompatibility: Claude Code >=1.0\nmetadata:\n category: backend\n---\n\n# Falcon API Integration in Functions\n\n> Call Falcon APIs through the CrowdStrike SDKs inside Foundry function handlers. Authentication is automatic with the FDK handler pattern.\n>\n> The FalconPy `Detects` class is **deprecated**: it still ships, but its API returns 405. Do not import it. Use `Alerts` for detection queries.\n\n> **Part of a suite.** If `development-workflow` has not already run, and this is a new app or its first capability, load the `development-workflow` skill first — it owns the CLI prerequisite check, scaffolding order, and manifest coordination.\n\nThis skill covers calling CrowdStrike Falcon APIs from within Foundry functions (serverless Go or Python code). Authentication is completely automatic when code runs inside Foundry function handlers — the platform handles all OAuth flows, token management, and credential injection.\n\nFor exposing external APIs to Foundry via OpenAPI specs, see **api-integrations** instead.\n\n> **🚫 DEPRECATED API — NEVER USE:**\n>\n> **Do NOT import or use the `Detects` class from FalconPy.** The Detects API (`/detects/entities/detects/v2`) is deprecated and returns **405 Method Not Allowed**. Any code using `Detects()`, `query_detects()`, or `get_detect_summaries()` will fail at runtime.\n>\n> **Use instead:** `from falconpy import Alerts` with `query_alerts_v2()` / `get_alerts_v2()`. Filter by `product:'epp'` to scope to endpoint detections.\n\n## Reference Files\n\n| Topic | Reference |\n|-------|-----------|\n| Retry, worker threads, shared-CID listing, Workflows API as the app, enrichment | [references/advanced-patterns.md](references/advanced-patterns.md) |\n\n## Python: Zero-Argument Authentication\n\nFalconPy Service Classes require zero arguments when called inside Foundry Function handlers. The `crowdstrike.foundry.function` FDK provides the handler decorator that enables automatic authentication:\n\n```python\nfrom logging import Logger\nfrom typing import Any, Dict, Union\nfrom crowdstrike.foundry.function import Function, Request, Response\nfrom falconpy import Alerts, Hosts\n\nfunc = Function.instance()\n\n@func.handler(method='GET', path='/api/alerts')\ndef get_alerts(request: Request, config: Union[Dict[str, Any], None], logger: Logger) -> Response:\n falcon = Alerts() # Zero-arg constructor — auth is automatic\n\n limit = min(int(request.params.query.get(\"limit\", [\"50\"])[0]), 100)\n # FQL filter: high-severity alerts from the last 24 hours.\n # Combine conditions with '+' (AND); relative times like 'now-24h' are supported.\n response = falcon.query_alerts_v2(\n filter=\"severity_name:'High'+created_timestamp:>'now-24h'\",\n limit=limit,\n sort=\"created_timestamp|desc\",\n )\n\n if response[\"status_code\"] != 200:\n logger.error(f\"Failed to query alerts: {response.get('errors')}\")\n return Response(body={\"error\": \"Failed to fetch alerts\"}, code=500)\n\n alert_ids = response.get(\"body\", {}).get(\"resources\", [])\n if not alert_ids:\n return Response(body={\"alerts\": []}, code=200)\n\n details_response = falcon.get_alerts_v2(composite_ids=alert_ids)\n if details_response[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to fetch alert details\"}, code=500)\n\n alerts = details_response.get(\"body\", {}).get(\"resources\", [])\n return Response(body={\"alerts\": alerts}, code=200)\n\nif __name__ == '__main__':\n func.run()\n```\n\n**How it works:**\n- **In Foundry cloud**: Uses context-based authentication injected by the platform\n- **Locally**: Reads `FALCON_CLIENT_ID` and `FALCON_CLIENT_SECRET` from environment variables\n\nFalconPy already reads env vars internally, so writing a `get_falcon_client()` wrapper adds no value and breaks context auth in the cloud.\n\n\n## Go: FDK Helper Authentication\n\nGo requires the FDK helper to get cloud and user-agent configuration:\n\n```go\npackage main\n\nimport (\n \"context\"\n \"log/slog\"\n\n fdk \"github.com/CrowdStrike/foundry-fn-go\"\n \"github.com/crowdstrike/gofalcon/falcon\"\n)\n\nfunc newHandler(_ context.Context, _ *slog.Logger, _ fdk.SkipCfg) fdk.Handler {\n m := fdk.NewMux()\n\n m.Get(\"/api/alerts\", fdk.HandleFnOf(func(ctx context.Context, r fdk.RequestOf[struct{}]) fdk.Response {\n opts := fdk.FalconClientOpts()\n falconClient, err := falcon.NewClient(&falcon.ApiConfig{\n AccessToken: r.AccessToken,\n Cloud: falcon.Cloud(opts.Cloud),\n Context: ctx,\n UserAgentOverride: opts.UserAgent,\n })\n if err != nil {\n return fdk.Response{Code: 500, Body: fdk.JSON(map[string]string{\"error\": \"Failed to authenticate\"})}\n }\n\n _ = falconClient // call Falcon APIs here, e.g. falconClient.Alerts\n return fdk.Response{Code: 200, Body: fdk.JSON(map[string]interface{}{\"alerts\": []interface{}{}})}\n }))\n\n return m\n}\n\nfunc main() {\n fdk.Run(context.Background(), newHandler)\n}\n```\n\n## Common API Patterns\n\n### Detection Queries (via Alerts API)\n\n> **⚠️ The legacy Detects API (`/detects/entities/detects/v2`) is deprecated and returns 405 Method Not Allowed.** Use the Alerts API for all detection queries.\n\n```python\n@func.handler(method='GET', path='/api/detections')\ndef get_detections(request: Request, config, logger) -> Response:\n falcon = Alerts() # Zero-arg — auth is automatic\n\n severity_min = int(request.params.query.get(\"severity_min\", [\"70\"])[0]) # 1-100 scale\n limit = min(int(request.params.query.get(\"limit\", [\"50\"])[0]), 100)\n\n # query_alerts_v2 calls GET /alerts/queries/alerts/v2; get_alerts_v2 calls POST /alerts/entities/alerts/v2.\n # FQL filter: severity threshold + endpoint detections only.\n query_response = falcon.query_alerts_v2(\n filter=f\"severity:>={severity_min}+product:'epp'\",\n limit=limit,\n sort=\"created_timestamp|desc\",\n )\n if query_response[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to query detections\"}, code=500)\n\n alert_ids = query_response.get(\"body\", {}).get(\"resources\", [])\n if not alert_ids:\n return Response(body={\"detections\": []}, code=200)\n\n details = falcon.get_alerts_v2(composite_ids=alert_ids)\n if details[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to get details\"}, code=500)\n\n return Response(body={\"detections\": details[\"body\"][\"resources\"]}, code=200)\n```\n\n### Host Lookups\n\n```python\n@func.handler(method='GET', path='/api/hosts')\ndef get_host_details(request: Request, config, logger) -> Response:\n falcon = Hosts()\n\n hostname = request.params.query.get(\"hostname\", [\"\"])[0] # ?hostname=...\n if not hostname:\n return Response(body={\"error\": \"Hostname required\"}, code=400)\n\n query = falcon.query_devices_by_filter(filter=f\"hostname:'{hostname}'\")\n if query[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to query devices\"}, code=500)\n\n host_ids = query.get(\"body\", {}).get(\"resources\", [])\n if not host_ids:\n return Response(body={\"error\": f\"Host not found: {hostname}\"}, code=404)\n\n details = falcon.get_device_details(ids=host_ids)\n host = details.get(\"body\", {}).get(\"resources\", [{}])[0]\n return Response(body={\"host\": host}, code=200)\n```\n\n### Multi-API Enrichment\n\nCombining `Hosts` and `Alerts` in one handler follows the same query-then-get-details shape as above. See [references/advanced-patterns.md](references/advanced-patterns.md) for the full example.\n\n## LogScale / NG-SIEM Queries from Functions\n\nWhen you need to **query** LogScale data (e.g., workflow execution stats from the \"fusion\" repo, detection telemetry, custom ingested events), use the `NGSIEM` class. This is distinct from **ingestion** (covered in functions-development).\n\n> **⚠️ Class Disambiguation:**\n> - `NGSIEM` — Use for **querying** (async search jobs) and file uploads (lookup files, CSV imports). This is the query interface.\n> - `FoundryLogScale` — Use only for **ingestion** (`ingest_data`). Despite the name suggesting broad LogScale functionality, it does NOT have the search methods.\n\n### Query Pattern (Python)\n\n```python\nimport time\nfrom logging import Logger\nfrom typing import Any, Dict, Union\nfrom crowdstrike.foundry.function import Function, Request, Response\nfrom falconpy import NGSIEM\n\nfunc = Function.instance()\n\n# Always \"search-all\" — see the gotcha below. Scope to a repo in the query, not here.\nREPO = \"search-all\"\n\n\ndef run_logscale_query(ngsiem, query_string, start, end, logger, max_wait=40):\n \"\"\"Execute a CQL query as an async search job and return result rows.\n\n ``start`` / ``end`` accept Humio relative strings (\"24h\", \"7d\", \"30d\",\n \"now\") or epoch-millisecond integers.\n \"\"\"\n payload = {\"queryString\": query_string, \"start\": start, \"end\": end, \"isLive\": False}\n started = ngsiem.start_search(repository=REPO, search=payload)\n\n if not isinstance(started, dict) or started.get(\"status_code\", 500) >= 300:\n logger.error(f\"start_search failed: {started}\")\n return None\n\n # start_search returns \"resources\"; get_search_status returns \"body\".\n job_id = (started.get(\"resources\") or {}).get(\"id\")\n if not job_id:\n logger.error(f\"start_search returned no job id: {started}\")\n return None\n\n # Poll until done\n waited = 0.0\n poll_interval = 1.5\n while waited < max_wait:\n time.sleep(poll_interval)\n waited += poll_interval\n status = ngsiem.get_search_status(repository=REPO, id=job_id)\n if not isinstance(status, dict) or status.get(\"status_code\", 500) >= 300:\n logger.error(f\"get_search_status failed: {status}\")\n return None\n sbody = status.get(\"body\") or {}\n if sbody.get(\"done\"):\n return sbody.get(\"events\", []) or []\n\n logger.warning(f\"query timed out after {max_wait}s: {query_string}\")\n return None\n\n\n@func.handler(method='POST', path='/api/query')\ndef handle_query(request: Request, config: Union[Dict[str, Any], None], logger: Logger) -> Response:\n ngsiem = NGSIEM() # Zero-arg auth — automatic in Foundry\n\n query = request.body.get(\"query\", \"\")\n start = request.body.get(\"start\", \"24h\")\n end = request.body.get(\"end\", \"now\")\n\n events = run_logscale_query(ngsiem, query, start, end, logger)\n if events is None:\n return Response(body={\"error\": \"LogScale query failed\"}, code=500)\n\n return Response(body={\"results\": events, \"count\": len(events)}, code=200)\n\nif __name__ == '__main__':\n func.run()\n```\n\n### `start_search` Arguments and Responses\n\nPass the query to `start_search` as `search=`, as in the example above. Response keys are asymmetric: `start_search` renames its payload to `resources` (read `started[\"resources\"][\"id\"]`), while `get_search_status` does not (read `status[\"body\"]`).\n\n### The \"search-all\" Repository Gotcha\n\n**CRITICAL:** Always pass `repository=\"search-all\"` when querying from Foundry functions. Passing a specific repository name (e.g., `\"fusion\"`, `\"main\"`) causes **403 Forbidden** errors at runtime (`\"scope not permitted\"`), even if the repository exists and the app has `humio-auth-proxy` scopes granted.\n\nThe NG-SIEM queryjobs API is addressed by **searchable view**, not by raw repo name. Use `search-all` as the repository and add `#repo=fusion` (or whichever repo you need) as a filter prefix in your query string:\n\n```python\n# Filter to a specific repo within the query itself\nquery = \"#repo=fusion | execution_log_type=summary | execution_log_subtype=end | groupby([status], function=count(execution_id, distinct=true))\"\nevents = run_logscale_query(ngsiem, query, \"24h\", \"now\", logger)\n```\n\n### Required OAuth Scopes\n\n```yaml\n# manifest.yml\nauth:\n scopes:\n - humio-auth-proxy:read # Required for queries\n - humio-auth-proxy:write # Required only if also uploading lookup files\n```\n\n### Reference\n\n- [Exporting Falcon Next-Gen SIEM Query Results to CSV with Falcon Foundry](https://www.crowdstrike.com/tech-hub/ng-siem/exporting-falcon-next-gen-siem-query-results-to-csv-with-falcon-foundry/) — background on async LogScale querying from Foundry, plus CSV export. Note that this post reaches for `FoundryLogScale` with `mode=\"async\"`; the `NGSIEM` pattern above is what has been verified end-to-end against the queryjobs API in a deployed app. Use the pattern above, and treat the post as context for the surrounding workflow (time ranges, result handling, export).\n\n## Falcon Next-Gen SIEM Content APIs\n\nDashboards, saved queries, lookup files, and persisted aggregations take different search domain names, and a wrong one answers `404` or `400`, not `403`. See [ngsiem-content-apis](references/ngsiem-content-apis.md).\n\n## Charlotte AI AgentWorks (`/agentic-studio/*`)\n\nUse the `Agents`, `Spans`, `AgentInvocation`, `AgentVersions`, and `Models` classes with the `charlotte-ai-agent-definition` scopes (`read`; `write` to invoke and poll). Filter spans on `attributes.aw_agent.id` (not `aw_agent.agent_id`, which silently matches nothing). Route-to-method map: [advanced-patterns](references/advanced-patterns.md).\n\n## The 207 Multi-Status Gotcha\n\nCrowdStrike APIs may return `207 Multi-Status` responses that look successful but contain embedded errors. Check the errors array:\n\n```python\nresponse = falcon.perform_action(action_name=\"contain\", ids=host_ids)\n\nif response[\"status_code\"] == 207:\n errors = response.get(\"body\", {}).get(\"errors\", [])\n rate_limited = [e for e in errors if e.get(\"code\") == 429]\n if rate_limited:\n return Response(body={\"error\": \"Rate limited\", \"failed_ids\": [e.get(\"id\") for e in rate_limited]}, code=429)\n```\n\n## Testing\n\nMock Falcon APIs in tests instead of making real API calls (they are slow, flaky, and quota-consuming):\n\n```python\nimport importlib\nfrom unittest.mock import Mock, patch\n\nfrom crowdstrike.foundry.function import Request, RequestParams\n\nimport main\n\ndef test_get_alerts_success():\n mock_falcon = Mock()\n mock_falcon.query_alerts_v2.return_value = {\n \"status_code\": 200,\n \"body\": {\"resources\": [\"alert-001\", \"alert-002\"]}\n }\n mock_falcon.get_alerts_v2.return_value = {\n \"status_code\": 200,\n \"body\": {\"resources\": [{\"id\": \"alert-001\", \"severity\": 80}]}\n }\n\n # @func.handler registers the function and returns None, so swap in an\n # identity decorator and reload main (as foundry-sample-functions-python's tests do)\n with patch(\"crowdstrike.foundry.function.Function.handler\", new=lambda *a, **k: (lambda f: f)):\n importlib.reload(main)\n with patch(\"main.Alerts\", return_value=mock_falcon):\n request = Request(params=RequestParams(query={\"limit\": [\"10\"]}))\n response = main.get_alerts(request, None, Mock())\n assert response.code == 200\n assert len(response.body[\"alerts\"]) == 1\n # get_alerts_v2 reads only composite_ids; ids= fails with a 400 before any request is sent\n mock_falcon.get_alerts_v2.assert_called_once_with(composite_ids=[\"alert-001\", \"alert-002\"])\n```\n\n## Local Testing\n\n```bash\nexport FALCON_CLIENT_ID=\"your-client-id\"\nexport FALCON_CLIENT_SECRET=\"your-client-secret\"\ncd functions/my-function && python3 main.py\n# The FDK reads a JSON envelope, not the URL: POST it to the root with method, url, and params\ncurl -X POST http://localhost:8081 -H 'Content-Type: application/json' \\\n -d '{\"method\": \"GET\", \"url\": \"/api/alerts\", \"params\": {\"query\": {\"limit\": [\"10\"]}}}'\n```\n\n## OAuth Scopes for manifest.yml\n\nEvery FalconPy service class call requires the correct OAuth scope(s) declared in your manifest's `auth.scopes` array. Without them the function gets a 403 at runtime; `foundry apps validate` doesn't catch it.\n\n> **⚠️ Scope names don't always match class names.** `Hosts` needs `devices:read`, not `hosts:read`. Use this table, don't guess.\n\n> **Built-in capabilities don't need scopes.** API integrations, collections, and workflows work without declaring their scopes when used through Foundry's built-in SDK patterns (`falcon.apiIntegration()`, `CustomStorage()` for app collections, etc.). Only declare scopes when calling Falcon platform APIs directly via FalconPy service classes.\n\n### Scope Reference\n\nEach row is verified against a sample app's manifest, a live CID, or the API swagger.\n\n| FalconPy Class | Methods | Required Scope(s) | Verified In |\n|---|---|---|---|\n| `Hosts` | `get_device_details` | `devices:read` | foundry-sample-functions-python |\n| `Intel` | `query_indicator_ids` | `falconx-indicators:read` | foundry-sample-zscaler-internet-access |\n| `IdentityProtection` | `graphql`, `query_sensors`, `get_sensor_details` | `identity-graphql:write`, `identity-entities:read` | foundry-sample-idp-notifications |\n| `IdentityProtection` | `query_policy_rules`, `get_policy_rules`, `delete_policy_rules` | `identity-policy-rules:read`, `identity-policy-rules:write` | foundry-sample-servicenow-idp |\n| `NGSIEM` | `upload_file` | `humio-auth-proxy:write` | foundry-sample-ngsiem-importer |\n| `NGSIEM` | `start_search`, `get_search_status` | `humio-auth-proxy:read` | Verified against a live CID (200 + results); see LogScale Queries section |\n| `NGSIEM` | `/ngsiem-content/` calls | See [ngsiem-content-apis](references/ngsiem-content-apis.md) | Live CID |\n| `FoundryLogScale` | `ingest_data` | `app-logs:read`, `app-logs:write` | foundry-sample-logscale |\n| `FirewallManagement` | `create_rule_group`, `query_events`, `get_events` | `firewall-management:read`, `firewall-management:write` | foundry-sample-category-blocking |\n| `HostGroup` | `query_host_groups`, `get_host_groups` | `host-group:read`, `host-group:write` | foundry-sample-category-blocking |\n| `Agents`, `Spans`, `AgentInvocation`, `AgentVersions`, `Models` | AgentWorks | `charlotte-ai-agent-definition:read`, `:write` | Endpoints verified on EU-1 |\n| `CaseManagement` | `query_case_ids`, `get_cases` / `update_case_fields` | `cases:read` / `cases:write` | API swagger |\n| `RealTimeResponse` | `batch_init_sessions`, `batch_command` / `batch_active_responder_command` (incl. `runscript`) | `real-time-response:read` / `:write` | API swagger |\n| `RealTimeResponseAdmin` | `batch_admin_command` (`put`, `run`) | `real-time-response-admin:write` | API swagger |\n\n**Go functions (gofalcon) need the same scopes.** Incidents use `incidents:read` / `:write`.\n\n### How to declare scopes\n\n```yaml\n# manifest.yml\nauth:\n scopes:\n - devices:read\n - falconx-indicators:read\n permissions: {}\n roles: []\n```\n\n### When unsure about the correct scope\n\nIf you're using a FalconPy method not in this table:\n1. Check the method's HTTP verb and API path in FalconPy source — GET typically needs `:read`, POST/PUT/PATCH/DELETE typically needs `:write`\n2. The scope prefix is usually the **API path prefix** (e.g., `/iocs/...` → `iocs`, `/devices/...` → `devices`), but exceptions exist (`Hosts` → `devices`, `/humio/` → `humio-auth-proxy`, `/ngsiem-content/` → one per type)\n3. When ambiguous, **ask the user** which scopes to include rather than guessing\n\n## Falcon Severity Values\n\nAlerts carry `severity` as an integer from 1 to 100 (100 is most severe) and `severity_name` as its label, for example `30` / `\"Low\"` and `70` / `\"High\"`. Filter on `severity_name:'High'` or a numeric threshold such as `severity:>=70`; a low threshold like `severity:>=3` matches almost every alert. The `max_severity` / `max_severity_displayname` fields belong to the deprecated Detects API. When passing severity to an external system (Jira, ServiceNow, email), map `severity_name` to its expected values instead of passing the raw number through.\n\n## Common Pitfalls\n\n- **Writing OAuth code or credential management.** Auth is automatic inside FDK handlers. The zero-arg pattern (`Hosts()`, `Alerts()`) handles all auth. (Go requires `fdk.FalconClientOpts()` -- see above.)\n- **Using `requests` library instead of CrowdStrike SDKs.** SDKs handle auth, retries, pagination, and region discovery.\n- **Passing credentials explicitly to constructors.** Use zero-arg constructors (`Alerts()`, `Hosts()`). Do NOT write `IOC(client_id=os.environ[\"FALCON_CLIENT_ID\"], client_secret=...)` -- this breaks context-based auth in the Foundry cloud.\n- **Writing Falcon API calls outside of FDK handler functions.** The handler pattern is required for automatic auth injection.\n- **Module-scope client, or `request.params.get()` / `request.query`.** `401` on every call, or an attribute error.\n- **Not handling 207 Multi-Status.** These responses look successful but may contain embedded errors.\n\n## Use Cases\n\nFor real-world implementation patterns, see:\n- `use-cases/python-functions.md` — Python handler patterns, SDK usage, testing\n\n## Reference Implementations\n\n- **[foundry-sample-functions-python](https://github.com/CrowdStrike/foundry-sample-functions-python)**: Reference Python patterns. See also [Dive into Falcon Foundry Functions with Python](https://www.crowdstrike.com/tech-hub/ng-siem/dive-into-falcon-foundry-functions-with-python/).\n- **[foundry-sample-anomali-threatstream](https://github.com/CrowdStrike/foundry-sample-anomali-threatstream)**: Side-by-side Go and Python auth patterns.\n- **[foundry-sample-idp-notifications](https://github.com/CrowdStrike/foundry-sample-idp-notifications)**: Falcon IdP domain and connector monitoring.\n"AFTER
"---\nname: functions-falcon-api\ndescription: Call CrowdStrike Falcon platform APIs (detections, alerts, hosts, RTR) from within Foundry function handlers. TRIGGER when user asks to \"call Falcon APIs from a function\", \"use FalconPy in a function\", \"use gofalcon in a function\", or needs to integrate Falcon platform APIs within serverless function code. DO NOT TRIGGER when user wants to expose external third-party APIs to Foundry — use api-integrations instead.\nversion: 1.7.1\nupdated: 2026-11-10\ntags: [foundry, functions, falcon-api, falconpy, gofalcon]\nauthor: CrowdStrike\nlicense: MIT\ncompatibility: Claude Code >=1.0\nmetadata:\n category: backend\n---\n\n# Falcon API Integration in Functions\n\n> Call Falcon APIs through the CrowdStrike SDKs inside Foundry function handlers. Authentication is automatic with the FDK handler pattern.\n>\n> The FalconPy `Detects` class is **deprecated**: it still ships, but its API returns 405. Do not import it. Use `Alerts` for detection queries.\n\n> **Part of a suite.** If `development-workflow` has not already run, and this is a new app or its first capability, load the `development-workflow` skill first — it owns the CLI prerequisite check, scaffolding order, and manifest coordination.\n\nThis skill covers calling CrowdStrike Falcon APIs from within Foundry functions (serverless Go or Python code). Authentication is completely automatic when code runs inside Foundry function handlers — the platform handles all OAuth flows, token management, and credential injection.\n\nFor exposing external APIs to Foundry via OpenAPI specs, see **api-integrations** instead.\n\n> **🚫 DEPRECATED API — NEVER USE:**\n>\n> **Do NOT import or use the `Detects` class from FalconPy.** The Detects API (`/detects/entities/detects/v2`) is deprecated and returns **405 Method Not Allowed**. Any code using `Detects()`, `query_detects()`, or `get_detect_summaries()` will fail at runtime.\n>\n> **Use instead:** `from falconpy import Alerts` with `query_alerts_v2()` / `get_alerts_v2()`. Filter by `product:'epp'` to scope to endpoint detections.\n\n## Reference Files\n\n| Topic | Reference |\n|-------|-----------|\n| Retry, worker threads, shared-CID listing, Workflows API as the app, enrichment | [references/advanced-patterns.md](references/advanced-patterns.md) |\n\n## Python: Zero-Argument Authentication\n\nFalconPy Service Classes require zero arguments when called inside Foundry Function handlers. The `crowdstrike.foundry.function` FDK provides the handler decorator that enables automatic authentication:\n\n```python\nfrom logging import Logger\nfrom typing import Any, Dict, Union\nfrom crowdstrike.foundry.function import Function, Request, Response\nfrom falconpy import Alerts, Hosts\n\nfunc = Function.instance()\n\n@func.handler(method='GET', path='/api/alerts')\ndef get_alerts(request: Request, config: Union[Dict[str, Any], None], logger: Logger) -> Response:\n falcon = Alerts() # Zero-arg constructor — auth is automatic\n\n limit = min(int(request.params.query.get(\"limit\", [\"50\"])[0]), 100)\n # FQL filter: high-severity alerts from the last 24 hours.\n # Combine conditions with '+' (AND); relative times like 'now-24h' are supported.\n response = falcon.query_alerts_v2(\n filter=\"severity_name:'High'+created_timestamp:>'now-24h'\",\n limit=limit,\n sort=\"created_timestamp|desc\",\n )\n\n if response[\"status_code\"] != 200:\n logger.error(f\"Failed to query alerts: {response.get('errors')}\")\n return Response(body={\"error\": \"Failed to fetch alerts\"}, code=500)\n\n alert_ids = response.get(\"body\", {}).get(\"resources\", [])\n if not alert_ids:\n return Response(body={\"alerts\": []}, code=200)\n\n details_response = falcon.get_alerts_v2(composite_ids=alert_ids)\n if details_response[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to fetch alert details\"}, code=500)\n\n alerts = details_response.get(\"body\", {}).get(\"resources\", [])\n return Response(body={\"alerts\": alerts}, code=200)\n\nif __name__ == '__main__':\n func.run()\n```\n\n**How it works:**\n- **In Foundry cloud**: Uses context-based authentication injected by the platform\n- **Locally**: Reads `FALCON_CLIENT_ID` and `FALCON_CLIENT_SECRET` from environment variables\n\nFalconPy already reads env vars internally, so writing a `get_falcon_client()` wrapper adds no value and breaks context auth in the cloud.\n\n\n## Go: FDK Helper Authentication\n\nGo requires the FDK helper to get cloud and user-agent configuration:\n\n```go\npackage main\n\nimport (\n \"context\"\n \"log/slog\"\n\n fdk \"github.com/CrowdStrike/foundry-fn-go\"\n \"github.com/crowdstrike/gofalcon/falcon\"\n)\n\nfunc newHandler(_ context.Context, _ *slog.Logger, _ fdk.SkipCfg) fdk.Handler {\n m := fdk.NewMux()\n\n m.Get(\"/api/alerts\", fdk.HandleFnOf(func(ctx context.Context, r fdk.RequestOf[struct{}]) fdk.Response {\n opts := fdk.FalconClientOpts()\n falconClient, err := falcon.NewClient(&falcon.ApiConfig{\n AccessToken: r.AccessToken,\n Cloud: falcon.Cloud(opts.Cloud),\n Context: ctx,\n UserAgentOverride: opts.UserAgent,\n })\n if err != nil {\n return fdk.Response{Code: 500, Body: fdk.JSON(map[string]string{\"error\": \"Failed to authenticate\"})}\n }\n\n _ = falconClient // call Falcon APIs here, e.g. falconClient.Alerts\n return fdk.Response{Code: 200, Body: fdk.JSON(map[string]interface{}{\"alerts\": []interface{}{}})}\n }))\n\n return m\n}\n\nfunc main() {\n fdk.Run(context.Background(), newHandler)\n}\n```\n\n## Common API Patterns\n\n### Detection Queries (via Alerts API)\n\n> **⚠️ The legacy Detects API (`/detects/entities/detects/v2`) is deprecated and returns 405 Method Not Allowed.** Use the Alerts API for all detection queries.\n\n```python\n@func.handler(method='GET', path='/api/detections')\ndef get_detections(request: Request, config, logger) -> Response:\n falcon = Alerts() # Zero-arg — auth is automatic\n\n severity_min = int(request.params.query.get(\"severity_min\", [\"70\"])[0]) # 1-100 scale\n limit = min(int(request.params.query.get(\"limit\", [\"50\"])[0]), 100)\n\n # query_alerts_v2 calls GET /alerts/queries/alerts/v2; get_alerts_v2 calls POST /alerts/entities/alerts/v2.\n # FQL filter: severity threshold + endpoint detections only.\n query_response = falcon.query_alerts_v2(\n filter=f\"severity:>={severity_min}+product:'epp'\",\n limit=limit,\n sort=\"created_timestamp|desc\",\n )\n if query_response[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to query detections\"}, code=500)\n\n alert_ids = query_response.get(\"body\", {}).get(\"resources\", [])\n if not alert_ids:\n return Response(body={\"detections\": []}, code=200)\n\n details = falcon.get_alerts_v2(composite_ids=alert_ids)\n if details[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to get details\"}, code=500)\n\n return Response(body={\"detections\": details[\"body\"][\"resources\"]}, code=200)\n```\n\n### Host Lookups\n\n```python\n@func.handler(method='GET', path='/api/hosts')\ndef get_host_details(request: Request, config, logger) -> Response:\n falcon = Hosts()\n\n hostname = request.params.query.get(\"hostname\", [\"\"])[0] # ?hostname=...\n if not hostname:\n return Response(body={\"error\": \"Hostname required\"}, code=400)\n\n query = falcon.query_devices_by_filter(filter=f\"hostname:'{hostname}'\")\n if query[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to query devices\"}, code=500)\n\n host_ids = query.get(\"body\", {}).get(\"resources\", [])\n if not host_ids:\n return Response(body={\"error\": f\"Host not found: {hostname}\"}, code=404)\n\n details = falcon.get_device_details(ids=host_ids)\n host = details.get(\"body\", {}).get(\"resources\", [{}])[0]\n return Response(body={\"host\": host}, code=200)\n```\n\n### Multi-API Enrichment\n\nCombining `Hosts` and `Alerts` in one handler follows the same query-then-get-details shape as above. See [references/advanced-patterns.md](references/advanced-patterns.md) for the full example.\n\n## LogScale / NG-SIEM Queries from Functions\n\nWhen you need to **query** LogScale data (e.g., workflow execution stats from the \"fusion\" repo, detection telemetry, custom ingested events), use the `NGSIEM` class. This is distinct from **ingestion** (covered in functions-development).\n\n> **⚠️ Class Disambiguation:**\n> - `NGSIEM` — Use for **querying** (async search jobs) and file uploads (lookup files, CSV imports). This is the query interface.\n> - `FoundryLogScale` — Use only for **ingestion** (`ingest_data`). Despite the name suggesting broad LogScale functionality, it does NOT have the search methods.\n\n### Query Pattern (Python)\n\n```python\nimport time\nfrom logging import Logger\nfrom typing import Any, Dict, Union\nfrom crowdstrike.foundry.function import Function, Request, Response\nfrom falconpy import NGSIEM\n\nfunc = Function.instance()\n\n# Always \"search-all\" — see the gotcha below. Scope to a repo in the query, not here.\nREPO = \"search-all\"\n\n\ndef run_logscale_query(ngsiem, query_string, start, end, logger, max_wait=40):\n \"\"\"Execute a CQL query as an async search job and return result rows.\n\n ``start`` / ``end`` accept Humio relative strings (\"24h\", \"7d\", \"30d\",\n \"now\") or epoch-millisecond integers.\n \"\"\"\n payload = {\"queryString\": query_string, \"start\": start, \"end\": end, \"isLive\": False}\n started = ngsiem.start_search(repository=REPO, search=payload)\n\n if not isinstance(started, dict) or started.get(\"status_code\", 500) >= 300:\n logger.error(f\"start_search failed: {started}\")\n return None\n\n # start_search returns \"resources\"; get_search_status returns \"body\".\n job_id = (started.get(\"resources\") or {}).get(\"id\")\n if not job_id:\n logger.error(f\"start_search returned no job id: {started}\")\n return None\n\n # Poll until done\n waited = 0.0\n poll_interval = 1.5\n while waited < max_wait:\n time.sleep(poll_interval)\n waited += poll_interval\n status = ngsiem.get_search_status(repository=REPO, id=job_id)\n if not isinstance(status, dict) or status.get(\"status_code\", 500) >= 300:\n logger.error(f\"get_search_status failed: {status}\")\n return None\n sbody = status.get(\"body\") or {}\n if sbody.get(\"done\"):\n return sbody.get(\"events\", []) or []\n\n logger.warning(f\"query timed out after {max_wait}s: {query_string}\")\n return None\n\n\n@func.handler(method='POST', path='/api/query')\ndef handle_query(request: Request, config: Union[Dict[str, Any], None], logger: Logger) -> Response:\n ngsiem = NGSIEM() # Zero-arg auth — automatic in Foundry\n\n query = request.body.get(\"query\", \"\")\n start = request.body.get(\"start\", \"24h\")\n end = request.body.get(\"end\", \"now\")\n\n events = run_logscale_query(ngsiem, query, start, end, logger)\n if events is None:\n return Response(body={\"error\": \"LogScale query failed\"}, code=500)\n\n return Response(body={\"results\": events, \"count\": len(events)}, code=200)\n\nif __name__ == '__main__':\n func.run()\n```\n\n### `start_search` Arguments and Responses\n\nPass the query to `start_search` as `search=`, as in the example above. Response keys are asymmetric: `start_search` renames its payload to `resources` (read `started[\"resources\"][\"id\"]`), while `get_search_status` does not (read `status[\"body\"]`).\n\n### The \"search-all\" Repository Gotcha\n\n**CRITICAL:** Always pass `repository=\"search-all\"` when querying from Foundry functions. Passing a specific repository name (e.g., `\"fusion\"`, `\"main\"`) causes **403 Forbidden** errors at runtime (`\"scope not permitted\"`), even if the repository exists and the app has `humio-auth-proxy` scopes granted.\n\nThe NG-SIEM queryjobs API is addressed by **searchable view**, not by raw repo name. Use `search-all` as the repository and add `#repo=fusion` (or whichever repo you need) as a filter prefix in your query string:\n\n```python\n# Filter to a specific repo within the query itself\nquery = \"#repo=fusion | execution_log_type=summary | execution_log_subtype=end | groupby([status], function=count(execution_id, distinct=true))\"\nevents = run_logscale_query(ngsiem, query, \"24h\", \"now\", logger)\n```\n\n### Required OAuth Scopes\n\n```yaml\n# manifest.yml\nauth:\n scopes:\n - humio-auth-proxy:read # Required for queries\n - humio-auth-proxy:write # Required only if also uploading lookup files\n```\n\n### Reference\n\n- [Exporting Falcon Next-Gen SIEM Query Results to CSV with Falcon Foundry](https://www.crowdstrike.com/tech-hub/ng-siem/exporting-falcon-next-gen-siem-query-results-to-csv-with-falcon-foundry/) — background on async LogScale querying from Foundry, plus CSV export. Note that this post reaches for `FoundryLogScale` with `mode=\"async\"`; the `NGSIEM` pattern above is what has been verified end-to-end against the queryjobs API in a deployed app. Use the pattern above, and treat the post as context for the surrounding workflow (time ranges, result handling, export).\n\n## Falcon Next-Gen SIEM Content APIs\n\nDashboards, saved queries, lookup files, and persisted aggregations take different search domain names, and a wrong one answers `404` or `400`, not `403`. See [ngsiem-content-apis](references/ngsiem-content-apis.md).\n\n## Charlotte AI AgentWorks (`/agentic-studio/*`)\n\nUse the `Agents`, `Spans`, `AgentInvocation`, `AgentVersions`, and `Models` classes with the `charlotte-ai-agent-definition` scopes (`read`; `write` to invoke and poll). Filter spans on `attributes.aw_agent.id` (not `aw_agent.agent_id`, which silently matches nothing). Route-to-method map: [advanced-patterns](references/advanced-patterns.md).\n\n## The 207 Multi-Status Gotcha\n\nCrowdStrike APIs may return `207 Multi-Status` responses that look successful but contain embedded errors. Check the errors array:\n\n```python\nresponse = falcon.perform_action(action_name=\"contain\", ids=host_ids)\n\nif response[\"status_code\"] == 207:\n errors = response.get(\"body\", {}).get(\"errors\", [])\n rate_limited = [e for e in errors if e.get(\"code\") == 429]\n if rate_limited:\n return Response(body={\"error\": \"Rate limited\", \"failed_ids\": [e.get(\"id\") for e in rate_limited]}, code=429)\n```\n\n## Testing\n\nMock Falcon APIs in tests instead of making real API calls (they are slow, flaky, and quota-consuming):\n\n```python\nimport importlib\nfrom unittest.mock import Mock, patch\n\nfrom crowdstrike.foundry.function import Request, RequestParams\n\nimport main\n\ndef test_get_alerts_success():\n mock_falcon = Mock()\n mock_falcon.query_alerts_v2.return_value = {\n \"status_code\": 200,\n \"body\": {\"resources\": [\"alert-001\", \"alert-002\"]}\n }\n mock_falcon.get_alerts_v2.return_value = {\n \"status_code\": 200,\n \"body\": {\"resources\": [{\"id\": \"alert-001\", \"severity\": 80}]}\n }\n\n # @func.handler registers the function and returns None, so swap in an\n # identity decorator and reload main (as foundry-sample-functions-python's tests do)\n with patch(\"crowdstrike.foundry.function.Function.handler\", new=lambda *a, **k: (lambda f: f)):\n importlib.reload(main)\n with patch(\"main.Alerts\", return_value=mock_falcon):\n request = Request(params=RequestParams(query={\"limit\": [\"10\"]}))\n response = main.get_alerts(request, None, Mock())\n assert response.code == 200\n assert len(response.body[\"alerts\"]) == 1\n # get_alerts_v2 reads only composite_ids; ids= fails with a 400 before any request is sent\n mock_falcon.get_alerts_v2.assert_called_once_with(composite_ids=[\"alert-001\", \"alert-002\"])\n```\n\n## Local Testing\n\n```bash\nexport FALCON_CLIENT_ID=\"your-client-id\"\nexport FALCON_CLIENT_SECRET=\"your-client-secret\"\ncd functions/my-function && python3 main.py\n# The FDK reads a JSON envelope, not the URL: POST it to the root with method, url, and params\ncurl -X POST http://localhost:8081 -H 'Content-Type: application/json' \\\n -d '{\"method\": \"GET\", \"url\": \"/api/alerts\", \"params\": {\"query\": {\"limit\": [\"10\"]}}}'\n```\n\n## OAuth Scopes for manifest.yml\n\nEvery FalconPy service class call requires the correct OAuth scope(s) declared in your manifest's `auth.scopes` array. Without them the function gets a 403 at runtime; `foundry apps validate` doesn't catch it.\n\n> **⚠️ Scope names don't always match class names.** `Hosts` needs `devices:read`, not `hosts:read`. Use this table, don't guess.\n\n> **Built-in capabilities don't need scopes.** API integrations, collections, and workflows work without declaring their scopes when used through Foundry's built-in SDK patterns (`falcon.apiIntegration()`, `CustomStorage()` for app collections, etc.). Only declare scopes when calling Falcon platform APIs directly via FalconPy service classes.\n\n### Scope Reference\n\nEach row is verified against a sample app's manifest, a live CID, or the API swagger.\n\n| FalconPy Class | Methods | Required Scope(s) | Verified In |\n|---|---|---|---|\n| `Hosts` | `get_device_details` | `devices:read` | foundry-sample-functions-python |\n| `Intel` | `query_indicator_ids` | `falconx-indicators:read` | foundry-sample-zscaler-internet-access |\n| `IdentityProtection` | `graphql`, `query_sensors`, `get_sensor_details` | `identity-graphql:write`, `identity-entities:read` | foundry-sample-idp-notifications |\n| `IdentityProtection` | `query_policy_rules`, `get_policy_rules`, `delete_policy_rules` | `identity-policy-rules:read`, `identity-policy-rules:write` | foundry-sample-servicenow-idp |\n| `NGSIEM` | `upload_file` | `humio-auth-proxy:write` | foundry-sample-ngsiem-importer |\n| `NGSIEM` | `start_search`, `get_search_status` | `humio-auth-proxy:read` | Verified against a live CID (200 + results); see LogScale Queries section |\n| `NGSIEM` | `/ngsiem-content/` calls | See [ngsiem-content-apis](references/ngsiem-content-apis.md) | Live CID |\n| `FoundryLogScale` | `ingest_data` | `app-logs:read`, `app-logs:write` | foundry-sample-logscale |\n| `FirewallManagement` | `create_rule_group`, `query_events`, `get_events` | `firewall-management:read`, `firewall-management:write` | foundry-sample-category-blocking |\n| `HostGroup` | `query_host_groups`, `get_host_groups` | `host-group:read`, `host-group:write` | foundry-sample-category-blocking |\n| `Agents`, `Spans`, `AgentInvocation`, `AgentVersions`, `Models` | AgentWorks | `charlotte-ai-agent-definition:read`, `:write` | Endpoints verified on EU-1 |\n| `CaseManagement` | `query_case_ids`, `get_cases` / `update_case_fields` | `cases:read` / `cases:write` | API swagger |\n| `RealTimeResponse` | `batch_init_sessions`, `batch_command` / `batch_active_responder_command` (incl. `runscript`) | `real-time-response:read` / `:write` | API swagger |\n| `RealTimeResponseAdmin` | `batch_admin_command` (`put`, `run`) | `real-time-response-admin:write` | API swagger |\n\n**Go functions (gofalcon) need the same scopes.** Incidents use `incidents:read` / `:write`.\n\n### How to declare scopes\n\n```yaml\n# manifest.yml\nauth:\n scopes:\n - devices:read\n - falconx-indicators:read\n permissions: {}\n roles: []\n```\n\n### When unsure about the correct scope\n\nIf you're using a FalconPy method not in this table:\n1. Check the method's HTTP verb and API path in FalconPy source — GET typically needs `:read`, POST/PUT/PATCH/DELETE typically needs `:write`\n2. The scope prefix is usually the **API path prefix** (e.g., `/iocs/...` → `iocs`, `/devices/...` → `devices`), but exceptions exist (`Hosts` → `devices`, `/humio/` → `humio-auth-proxy`, `/ngsiem-content/` → one per type)\n3. When ambiguous, **ask the user** which scopes to include rather than guessing\n\n## Falcon Severity Values\n\nAlerts carry `severity` as an integer from 1 to 100 (100 is most severe) and `severity_name` as its label, for example `30` / `\"Low\"` and `70` / `\"High\"`. Filter on `severity_name:'High'` or a numeric threshold such as `severity:>=70`; a low threshold like `severity:>=3` matches almost every alert. The `max_severity` / `max_severity_displayname` fields belong to the deprecated Detects API. When passing severity to an external system (Jira, ServiceNow, email), map `severity_name` to its expected values instead of passing the raw number through.\n\n## Common Pitfalls\n\n- **Writing OAuth code or credential management.** Auth is automatic inside FDK handlers. The zero-arg pattern (`Hosts()`, `Alerts()`) handles all auth. (Go requires `fdk.FalconClientOpts()` -- see above.)\n- **Using `requests` library instead of CrowdStrike SDKs.** SDKs handle auth, retries, pagination, and region discovery.\n- **Passing credentials explicitly to constructors.** Use zero-arg constructors (`Alerts()`, `Hosts()`). Do NOT write `IOC(client_id=os.environ[\"FALCON_CLIENT_ID\"], client_secret=...)` -- this breaks context-based auth in the Foundry cloud.\n- **Writing Falcon API calls outside of FDK handler functions.** The handler pattern is required for automatic auth injection.\n- **Module-scope client, or `request.params.get()` / `request.query`.** `401` on every call, or an attribute error.\n- **Not handling 207 Multi-Status.** These responses look successful but may contain embedded errors.\n\n## Use Cases\n\nFor real-world implementation patterns, see:\n- `use-cases/python-functions.md` — Python handler patterns, SDK usage, testing\n\n## Reference Implementations\n\n- **[foundry-sample-functions-python](https://github.com/CrowdStrike/foundry-sample-functions-python)**: Reference Python patterns. See also [Dive into Falcon Foundry Functions with Python](https://www.crowdstrike.com/tech-hub/ng-siem/dive-into-falcon-foundry-functions-with-python/).\n- **[foundry-sample-anomali-threatstream](https://github.com/CrowdStrike/foundry-sample-anomali-threatstream)**: Side-by-side Go and Python auth patterns.\n- **[foundry-sample-idp-notifications](https://github.com/CrowdStrike/foundry-sample-idp-notifications)**: Falcon IdP domain and connector monitoring.\n"Full snapshot data
{
"description": "Call CrowdStrike Falcon platform APIs (detections, alerts, hosts, RTR) from within Foundry function handlers. TRIGGER when user asks to \"call Falcon APIs from a function\", \"use FalconPy in a function\", \"use gofalcon in a function\", or needs to integrate Falcon platform APIs within serverless function code. DO NOT TRIGGER when user wants to expose external third-party APIs to Foundry — use api-integrations instead.",
"included_files": [
{
"relative_path": "references/advanced-patterns.md",
"size_in_bytes": 11699
},
{
"relative_path": "references/ngsiem-content-apis.md",
"size_in_bytes": 5273
}
],
"name": "functions-falcon-api",
"skill_md_contents": "---\nname: functions-falcon-api\ndescription: Call CrowdStrike Falcon platform APIs (detections, alerts, hosts, RTR) from within Foundry function handlers. TRIGGER when user asks to \"call Falcon APIs from a function\", \"use FalconPy in a function\", \"use gofalcon in a function\", or needs to integrate Falcon platform APIs within serverless function code. DO NOT TRIGGER when user wants to expose external third-party APIs to Foundry — use api-integrations instead.\nversion: 1.7.1\nupdated: 2026-11-10\ntags: [foundry, functions, falcon-api, falconpy, gofalcon]\nauthor: CrowdStrike\nlicense: MIT\ncompatibility: Claude Code >=1.0\nmetadata:\n category: backend\n---\n\n# Falcon API Integration in Functions\n\n> Call Falcon APIs through the CrowdStrike SDKs inside Foundry function handlers. Authentication is automatic with the FDK handler pattern.\n>\n> The FalconPy `Detects` class is **deprecated**: it still ships, but its API returns 405. Do not import it. Use `Alerts` for detection queries.\n\n> **Part of a suite.** If `development-workflow` has not already run, and this is a new app or its first capability, load the `development-workflow` skill first — it owns the CLI prerequisite check, scaffolding order, and manifest coordination.\n\nThis skill covers calling CrowdStrike Falcon APIs from within Foundry functions (serverless Go or Python code). Authentication is completely automatic when code runs inside Foundry function handlers — the platform handles all OAuth flows, token management, and credential injection.\n\nFor exposing external APIs to Foundry via OpenAPI specs, see **api-integrations** instead.\n\n> **🚫 DEPRECATED API — NEVER USE:**\n>\n> **Do NOT import or use the `Detects` class from FalconPy.** The Detects API (`/detects/entities/detects/v2`) is deprecated and returns **405 Method Not Allowed**. Any code using `Detects()`, `query_detects()`, or `get_detect_summaries()` will fail at runtime.\n>\n> **Use instead:** `from falconpy import Alerts` with `query_alerts_v2()` / `get_alerts_v2()`. Filter by `product:'epp'` to scope to endpoint detections.\n\n## Reference Files\n\n| Topic | Reference |\n|-------|-----------|\n| Retry, worker threads, shared-CID listing, Workflows API as the app, enrichment | [references/advanced-patterns.md](references/advanced-patterns.md) |\n\n## Python: Zero-Argument Authentication\n\nFalconPy Service Classes require zero arguments when called inside Foundry Function handlers. The `crowdstrike.foundry.function` FDK provides the handler decorator that enables automatic authentication:\n\n```python\nfrom logging import Logger\nfrom typing import Any, Dict, Union\nfrom crowdstrike.foundry.function import Function, Request, Response\nfrom falconpy import Alerts, Hosts\n\nfunc = Function.instance()\n\n@func.handler(method='GET', path='/api/alerts')\ndef get_alerts(request: Request, config: Union[Dict[str, Any], None], logger: Logger) -> Response:\n falcon = Alerts() # Zero-arg constructor — auth is automatic\n\n limit = min(int(request.params.query.get(\"limit\", [\"50\"])[0]), 100)\n # FQL filter: high-severity alerts from the last 24 hours.\n # Combine conditions with '+' (AND); relative times like 'now-24h' are supported.\n response = falcon.query_alerts_v2(\n filter=\"severity_name:'High'+created_timestamp:>'now-24h'\",\n limit=limit,\n sort=\"created_timestamp|desc\",\n )\n\n if response[\"status_code\"] != 200:\n logger.error(f\"Failed to query alerts: {response.get('errors')}\")\n return Response(body={\"error\": \"Failed to fetch alerts\"}, code=500)\n\n alert_ids = response.get(\"body\", {}).get(\"resources\", [])\n if not alert_ids:\n return Response(body={\"alerts\": []}, code=200)\n\n details_response = falcon.get_alerts_v2(composite_ids=alert_ids)\n if details_response[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to fetch alert details\"}, code=500)\n\n alerts = details_response.get(\"body\", {}).get(\"resources\", [])\n return Response(body={\"alerts\": alerts}, code=200)\n\nif __name__ == '__main__':\n func.run()\n```\n\n**How it works:**\n- **In Foundry cloud**: Uses context-based authentication injected by the platform\n- **Locally**: Reads `FALCON_CLIENT_ID` and `FALCON_CLIENT_SECRET` from environment variables\n\nFalconPy already reads env vars internally, so writing a `get_falcon_client()` wrapper adds no value and breaks context auth in the cloud.\n\n\n## Go: FDK Helper Authentication\n\nGo requires the FDK helper to get cloud and user-agent configuration:\n\n```go\npackage main\n\nimport (\n \"context\"\n \"log/slog\"\n\n fdk \"github.com/CrowdStrike/foundry-fn-go\"\n \"github.com/crowdstrike/gofalcon/falcon\"\n)\n\nfunc newHandler(_ context.Context, _ *slog.Logger, _ fdk.SkipCfg) fdk.Handler {\n m := fdk.NewMux()\n\n m.Get(\"/api/alerts\", fdk.HandleFnOf(func(ctx context.Context, r fdk.RequestOf[struct{}]) fdk.Response {\n opts := fdk.FalconClientOpts()\n falconClient, err := falcon.NewClient(&falcon.ApiConfig{\n AccessToken: r.AccessToken,\n Cloud: falcon.Cloud(opts.Cloud),\n Context: ctx,\n UserAgentOverride: opts.UserAgent,\n })\n if err != nil {\n return fdk.Response{Code: 500, Body: fdk.JSON(map[string]string{\"error\": \"Failed to authenticate\"})}\n }\n\n _ = falconClient // call Falcon APIs here, e.g. falconClient.Alerts\n return fdk.Response{Code: 200, Body: fdk.JSON(map[string]interface{}{\"alerts\": []interface{}{}})}\n }))\n\n return m\n}\n\nfunc main() {\n fdk.Run(context.Background(), newHandler)\n}\n```\n\n## Common API Patterns\n\n### Detection Queries (via Alerts API)\n\n> **⚠️ The legacy Detects API (`/detects/entities/detects/v2`) is deprecated and returns 405 Method Not Allowed.** Use the Alerts API for all detection queries.\n\n```python\n@func.handler(method='GET', path='/api/detections')\ndef get_detections(request: Request, config, logger) -> Response:\n falcon = Alerts() # Zero-arg — auth is automatic\n\n severity_min = int(request.params.query.get(\"severity_min\", [\"70\"])[0]) # 1-100 scale\n limit = min(int(request.params.query.get(\"limit\", [\"50\"])[0]), 100)\n\n # query_alerts_v2 calls GET /alerts/queries/alerts/v2; get_alerts_v2 calls POST /alerts/entities/alerts/v2.\n # FQL filter: severity threshold + endpoint detections only.\n query_response = falcon.query_alerts_v2(\n filter=f\"severity:>={severity_min}+product:'epp'\",\n limit=limit,\n sort=\"created_timestamp|desc\",\n )\n if query_response[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to query detections\"}, code=500)\n\n alert_ids = query_response.get(\"body\", {}).get(\"resources\", [])\n if not alert_ids:\n return Response(body={\"detections\": []}, code=200)\n\n details = falcon.get_alerts_v2(composite_ids=alert_ids)\n if details[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to get details\"}, code=500)\n\n return Response(body={\"detections\": details[\"body\"][\"resources\"]}, code=200)\n```\n\n### Host Lookups\n\n```python\n@func.handler(method='GET', path='/api/hosts')\ndef get_host_details(request: Request, config, logger) -> Response:\n falcon = Hosts()\n\n hostname = request.params.query.get(\"hostname\", [\"\"])[0] # ?hostname=...\n if not hostname:\n return Response(body={\"error\": \"Hostname required\"}, code=400)\n\n query = falcon.query_devices_by_filter(filter=f\"hostname:'{hostname}'\")\n if query[\"status_code\"] != 200:\n return Response(body={\"error\": \"Failed to query devices\"}, code=500)\n\n host_ids = query.get(\"body\", {}).get(\"resources\", [])\n if not host_ids:\n return Response(body={\"error\": f\"Host not found: {hostname}\"}, code=404)\n\n details = falcon.get_device_details(ids=host_ids)\n host = details.get(\"body\", {}).get(\"resources\", [{}])[0]\n return Response(body={\"host\": host}, code=200)\n```\n\n### Multi-API Enrichment\n\nCombining `Hosts` and `Alerts` in one handler follows the same query-then-get-details shape as above. See [references/advanced-patterns.md](references/advanced-patterns.md) for the full example.\n\n## LogScale / NG-SIEM Queries from Functions\n\nWhen you need to **query** LogScale data (e.g., workflow execution stats from the \"fusion\" repo, detection telemetry, custom ingested events), use the `NGSIEM` class. This is distinct from **ingestion** (covered in functions-development).\n\n> **⚠️ Class Disambiguation:**\n> - `NGSIEM` — Use for **querying** (async search jobs) and file uploads (lookup files, CSV imports). This is the query interface.\n> - `FoundryLogScale` — Use only for **ingestion** (`ingest_data`). Despite the name suggesting broad LogScale functionality, it does NOT have the search methods.\n\n### Query Pattern (Python)\n\n```python\nimport time\nfrom logging import Logger\nfrom typing import Any, Dict, Union\nfrom crowdstrike.foundry.function import Function, Request, Response\nfrom falconpy import NGSIEM\n\nfunc = Function.instance()\n\n# Always \"search-all\" — see the gotcha below. Scope to a repo in the query, not here.\nREPO = \"search-all\"\n\n\ndef run_logscale_query(ngsiem, query_string, start, end, logger, max_wait=40):\n \"\"\"Execute a CQL query as an async search job and return result rows.\n\n ``start`` / ``end`` accept Humio relative strings (\"24h\", \"7d\", \"30d\",\n \"now\") or epoch-millisecond integers.\n \"\"\"\n payload = {\"queryString\": query_string, \"start\": start, \"end\": end, \"isLive\": False}\n started = ngsiem.start_search(repository=REPO, search=payload)\n\n if not isinstance(started, dict) or started.get(\"status_code\", 500) >= 300:\n logger.error(f\"start_search failed: {started}\")\n return None\n\n # start_search returns \"resources\"; get_search_status returns \"body\".\n job_id = (started.get(\"resources\") or {}).get(\"id\")\n if not job_id:\n logger.error(f\"start_search returned no job id: {started}\")\n return None\n\n # Poll until done\n waited = 0.0\n poll_interval = 1.5\n while waited < max_wait:\n time.sleep(poll_interval)\n waited += poll_interval\n status = ngsiem.get_search_status(repository=REPO, id=job_id)\n if not isinstance(status, dict) or status.get(\"status_code\", 500) >= 300:\n logger.error(f\"get_search_status failed: {status}\")\n return None\n sbody = status.get(\"body\") or {}\n if sbody.get(\"done\"):\n return sbody.get(\"events\", []) or []\n\n logger.warning(f\"query timed out after {max_wait}s: {query_string}\")\n return None\n\n\n@func.handler(method='POST', path='/api/query')\ndef handle_query(request: Request, config: Union[Dict[str, Any], None], logger: Logger) -> Response:\n ngsiem = NGSIEM() # Zero-arg auth — automatic in Foundry\n\n query = request.body.get(\"query\", \"\")\n start = request.body.get(\"start\", \"24h\")\n end = request.body.get(\"end\", \"now\")\n\n events = run_logscale_query(ngsiem, query, start, end, logger)\n if events is None:\n return Response(body={\"error\": \"LogScale query failed\"}, code=500)\n\n return Response(body={\"results\": events, \"count\": len(events)}, code=200)\n\nif __name__ == '__main__':\n func.run()\n```\n\n### `start_search` Arguments and Responses\n\nPass the query to `start_search` as `search=`, as in the example above. Response keys are asymmetric: `start_search` renames its payload to `resources` (read `started[\"resources\"][\"id\"]`), while `get_search_status` does not (read `status[\"body\"]`).\n\n### The \"search-all\" Repository Gotcha\n\n**CRITICAL:** Always pass `repository=\"search-all\"` when querying from Foundry functions. Passing a specific repository name (e.g., `\"fusion\"`, `\"main\"`) causes **403 Forbidden** errors at runtime (`\"scope not permitted\"`), even if the repository exists and the app has `humio-auth-proxy` scopes granted.\n\nThe NG-SIEM queryjobs API is addressed by **searchable view**, not by raw repo name. Use `search-all` as the repository and add `#repo=fusion` (or whichever repo you need) as a filter prefix in your query string:\n\n```python\n# Filter to a specific repo within the query itself\nquery = \"#repo=fusion | execution_log_type=summary | execution_log_subtype=end | groupby([status], function=count(execution_id, distinct=true))\"\nevents = run_logscale_query(ngsiem, query, \"24h\", \"now\", logger)\n```\n\n### Required OAuth Scopes\n\n```yaml\n# manifest.yml\nauth:\n scopes:\n - humio-auth-proxy:read # Required for queries\n - humio-auth-proxy:write # Required only if also uploading lookup files\n```\n\n### Reference\n\n- [Exporting Falcon Next-Gen SIEM Query Results to CSV with Falcon Foundry](https://www.crowdstrike.com/tech-hub/ng-siem/exporting-falcon-next-gen-siem-query-results-to-csv-with-falcon-foundry/) — background on async LogScale querying from Foundry, plus CSV export. Note that this post reaches for `FoundryLogScale` with `mode=\"async\"`; the `NGSIEM` pattern above is what has been verified end-to-end against the queryjobs API in a deployed app. Use the pattern above, and treat the post as context for the surrounding workflow (time ranges, result handling, export).\n\n## Falcon Next-Gen SIEM Content APIs\n\nDashboards, saved queries, lookup files, and persisted aggregations take different search domain names, and a wrong one answers `404` or `400`, not `403`. See [ngsiem-content-apis](references/ngsiem-content-apis.md).\n\n## Charlotte AI AgentWorks (`/agentic-studio/*`)\n\nUse the `Agents`, `Spans`, `AgentInvocation`, `AgentVersions`, and `Models` classes with the `charlotte-ai-agent-definition` scopes (`read`; `write` to invoke and poll). Filter spans on `attributes.aw_agent.id` (not `aw_agent.agent_id`, which silently matches nothing). Route-to-method map: [advanced-patterns](references/advanced-patterns.md).\n\n## The 207 Multi-Status Gotcha\n\nCrowdStrike APIs may return `207 Multi-Status` responses that look successful but contain embedded errors. Check the errors array:\n\n```python\nresponse = falcon.perform_action(action_name=\"contain\", ids=host_ids)\n\nif response[\"status_code\"] == 207:\n errors = response.get(\"body\", {}).get(\"errors\", [])\n rate_limited = [e for e in errors if e.get(\"code\") == 429]\n if rate_limited:\n return Response(body={\"error\": \"Rate limited\", \"failed_ids\": [e.get(\"id\") for e in rate_limited]}, code=429)\n```\n\n## Testing\n\nMock Falcon APIs in tests instead of making real API calls (they are slow, flaky, and quota-consuming):\n\n```python\nimport importlib\nfrom unittest.mock import Mock, patch\n\nfrom crowdstrike.foundry.function import Request, RequestParams\n\nimport main\n\ndef test_get_alerts_success():\n mock_falcon = Mock()\n mock_falcon.query_alerts_v2.return_value = {\n \"status_code\": 200,\n \"body\": {\"resources\": [\"alert-001\", \"alert-002\"]}\n }\n mock_falcon.get_alerts_v2.return_value = {\n \"status_code\": 200,\n \"body\": {\"resources\": [{\"id\": \"alert-001\", \"severity\": 80}]}\n }\n\n # @func.handler registers the function and returns None, so swap in an\n # identity decorator and reload main (as foundry-sample-functions-python's tests do)\n with patch(\"crowdstrike.foundry.function.Function.handler\", new=lambda *a, **k: (lambda f: f)):\n importlib.reload(main)\n with patch(\"main.Alerts\", return_value=mock_falcon):\n request = Request(params=RequestParams(query={\"limit\": [\"10\"]}))\n response = main.get_alerts(request, None, Mock())\n assert response.code == 200\n assert len(response.body[\"alerts\"]) == 1\n # get_alerts_v2 reads only composite_ids; ids= fails with a 400 before any request is sent\n mock_falcon.get_alerts_v2.assert_called_once_with(composite_ids=[\"alert-001\", \"alert-002\"])\n```\n\n## Local Testing\n\n```bash\nexport FALCON_CLIENT_ID=\"your-client-id\"\nexport FALCON_CLIENT_SECRET=\"your-client-secret\"\ncd functions/my-function && python3 main.py\n# The FDK reads a JSON envelope, not the URL: POST it to the root with method, url, and params\ncurl -X POST http://localhost:8081 -H 'Content-Type: application/json' \\\n -d '{\"method\": \"GET\", \"url\": \"/api/alerts\", \"params\": {\"query\": {\"limit\": [\"10\"]}}}'\n```\n\n## OAuth Scopes for manifest.yml\n\nEvery FalconPy service class call requires the correct OAuth scope(s) declared in your manifest's `auth.scopes` array. Without them the function gets a 403 at runtime; `foundry apps validate` doesn't catch it.\n\n> **⚠️ Scope names don't always match class names.** `Hosts` needs `devices:read`, not `hosts:read`. Use this table, don't guess.\n\n> **Built-in capabilities don't need scopes.** API integrations, collections, and workflows work without declaring their scopes when used through Foundry's built-in SDK patterns (`falcon.apiIntegration()`, `CustomStorage()` for app collections, etc.). Only declare scopes when calling Falcon platform APIs directly via FalconPy service classes.\n\n### Scope Reference\n\nEach row is verified against a sample app's manifest, a live CID, or the API swagger.\n\n| FalconPy Class | Methods | Required Scope(s) | Verified In |\n|---|---|---|---|\n| `Hosts` | `get_device_details` | `devices:read` | foundry-sample-functions-python |\n| `Intel` | `query_indicator_ids` | `falconx-indicators:read` | foundry-sample-zscaler-internet-access |\n| `IdentityProtection` | `graphql`, `query_sensors`, `get_sensor_details` | `identity-graphql:write`, `identity-entities:read` | foundry-sample-idp-notifications |\n| `IdentityProtection` | `query_policy_rules`, `get_policy_rules`, `delete_policy_rules` | `identity-policy-rules:read`, `identity-policy-rules:write` | foundry-sample-servicenow-idp |\n| `NGSIEM` | `upload_file` | `humio-auth-proxy:write` | foundry-sample-ngsiem-importer |\n| `NGSIEM` | `start_search`, `get_search_status` | `humio-auth-proxy:read` | Verified against a live CID (200 + results); see LogScale Queries section |\n| `NGSIEM` | `/ngsiem-content/` calls | See [ngsiem-content-apis](references/ngsiem-content-apis.md) | Live CID |\n| `FoundryLogScale` | `ingest_data` | `app-logs:read`, `app-logs:write` | foundry-sample-logscale |\n| `FirewallManagement` | `create_rule_group`, `query_events`, `get_events` | `firewall-management:read`, `firewall-management:write` | foundry-sample-category-blocking |\n| `HostGroup` | `query_host_groups`, `get_host_groups` | `host-group:read`, `host-group:write` | foundry-sample-category-blocking |\n| `Agents`, `Spans`, `AgentInvocation`, `AgentVersions`, `Models` | AgentWorks | `charlotte-ai-agent-definition:read`, `:write` | Endpoints verified on EU-1 |\n| `CaseManagement` | `query_case_ids`, `get_cases` / `update_case_fields` | `cases:read` / `cases:write` | API swagger |\n| `RealTimeResponse` | `batch_init_sessions`, `batch_command` / `batch_active_responder_command` (incl. `runscript`) | `real-time-response:read` / `:write` | API swagger |\n| `RealTimeResponseAdmin` | `batch_admin_command` (`put`, `run`) | `real-time-response-admin:write` | API swagger |\n\n**Go functions (gofalcon) need the same scopes.** Incidents use `incidents:read` / `:write`.\n\n### How to declare scopes\n\n```yaml\n# manifest.yml\nauth:\n scopes:\n - devices:read\n - falconx-indicators:read\n permissions: {}\n roles: []\n```\n\n### When unsure about the correct scope\n\nIf you're using a FalconPy method not in this table:\n1. Check the method's HTTP verb and API path in FalconPy source — GET typically needs `:read`, POST/PUT/PATCH/DELETE typically needs `:write`\n2. The scope prefix is usually the **API path prefix** (e.g., `/iocs/...` → `iocs`, `/devices/...` → `devices`), but exceptions exist (`Hosts` → `devices`, `/humio/` → `humio-auth-proxy`, `/ngsiem-content/` → one per type)\n3. When ambiguous, **ask the user** which scopes to include rather than guessing\n\n## Falcon Severity Values\n\nAlerts carry `severity` as an integer from 1 to 100 (100 is most severe) and `severity_name` as its label, for example `30` / `\"Low\"` and `70` / `\"High\"`. Filter on `severity_name:'High'` or a numeric threshold such as `severity:>=70`; a low threshold like `severity:>=3` matches almost every alert. The `max_severity` / `max_severity_displayname` fields belong to the deprecated Detects API. When passing severity to an external system (Jira, ServiceNow, email), map `severity_name` to its expected values instead of passing the raw number through.\n\n## Common Pitfalls\n\n- **Writing OAuth code or credential management.** Auth is automatic inside FDK handlers. The zero-arg pattern (`Hosts()`, `Alerts()`) handles all auth. (Go requires `fdk.FalconClientOpts()` -- see above.)\n- **Using `requests` library instead of CrowdStrike SDKs.** SDKs handle auth, retries, pagination, and region discovery.\n- **Passing credentials explicitly to constructors.** Use zero-arg constructors (`Alerts()`, `Hosts()`). Do NOT write `IOC(client_id=os.environ[\"FALCON_CLIENT_ID\"], client_secret=...)` -- this breaks context-based auth in the Foundry cloud.\n- **Writing Falcon API calls outside of FDK handler functions.** The handler pattern is required for automatic auth injection.\n- **Module-scope client, or `request.params.get()` / `request.query`.** `401` on every call, or an attribute error.\n- **Not handling 207 Multi-Status.** These responses look successful but may contain embedded errors.\n\n## Use Cases\n\nFor real-world implementation patterns, see:\n- `use-cases/python-functions.md` — Python handler patterns, SDK usage, testing\n\n## Reference Implementations\n\n- **[foundry-sample-functions-python](https://github.com/CrowdStrike/foundry-sample-functions-python)**: Reference Python patterns. See also [Dive into Falcon Foundry Functions with Python](https://www.crowdstrike.com/tech-hub/ng-siem/dive-into-falcon-foundry-functions-with-python/).\n- **[foundry-sample-anomali-threatstream](https://github.com/CrowdStrike/foundry-sample-anomali-threatstream)**: Side-by-side Go and Python auth patterns.\n- **[foundry-sample-idp-notifications](https://github.com/CrowdStrike/foundry-sample-idp-notifications)**: Falcon IdP domain and connector monitoring.\n"
}SHA-256 of public snapshot: e2fe2ae8fbda3f119eb1e48e0074699ef9612adf9c34c8ba1db9a55cdd1648ab