ioc-scope-api 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. ioc_scope_api-1.0.0.dist-info/METADATA +306 -0
  2. ioc_scope_api-1.0.0.dist-info/RECORD +106 -0
  3. ioc_scope_api-1.0.0.dist-info/WHEEL +4 -0
  4. ioc_scope_api-1.0.0.dist-info/entry_points.txt +2 -0
  5. scope/__init__.py +27 -0
  6. scope/api/__init__.py +119 -0
  7. scope/api/api_v1/__init__.py +2 -0
  8. scope/api/api_v1/api.py +71 -0
  9. scope/api/api_v1/endpoints/__init__.py +2 -0
  10. scope/api/api_v1/endpoints/agentic_protocols_metrics.py +39 -0
  11. scope/api/api_v1/endpoints/applications.py +440 -0
  12. scope/api/api_v1/endpoints/cache.py +50 -0
  13. scope/api/api_v1/endpoints/concepts.py +123 -0
  14. scope/api/api_v1/endpoints/features.py +19 -0
  15. scope/api/api_v1/endpoints/helpers.py +65 -0
  16. scope/api/api_v1/endpoints/kg.py +195 -0
  17. scope/api/api_v1/endpoints/labels.py +71 -0
  18. scope/api/api_v1/endpoints/live_topology.py +89 -0
  19. scope/api/api_v1/endpoints/metrics.py +1014 -0
  20. scope/api/api_v1/endpoints/reasoning.py +62 -0
  21. scope/api/api_v1/endpoints/semanticgroups.py +144 -0
  22. scope/api/api_v1/endpoints/sessions.py +339 -0
  23. scope/api/api_v1/endpoints/spans.py +41 -0
  24. scope/api/api_v1/endpoints/symbolic.py +186 -0
  25. scope/api/api_v1/endpoints/ui.py +145 -0
  26. scope/api/api_v1/endpoints/waste_estimation.py +182 -0
  27. scope/api/api_v2/__init__.py +3 -0
  28. scope/api/api_v2/api.py +23 -0
  29. scope/api/api_v2/endpoints/__init__.py +3 -0
  30. scope/api/api_v2/endpoints/metrics.py +193 -0
  31. scope/app.py +30 -0
  32. scope/cache.py +64 -0
  33. scope/client/__init__.py +27 -0
  34. scope/client/_concepts.py +137 -0
  35. scope/client/_kg.py +64 -0
  36. scope/client/_labels.py +86 -0
  37. scope/client/_live_topology.py +912 -0
  38. scope/client/_metrics.py +561 -0
  39. scope/client/_semanticgroups.py +166 -0
  40. scope/client/_sessions.py +168 -0
  41. scope/client/_symbolic.py +1354 -0
  42. scope/client/_ui.py +599 -0
  43. scope/client/agentic_protocols.py +289 -0
  44. scope/client/application_charts.py +1786 -0
  45. scope/client/applications.py +2246 -0
  46. scope/client/base.py +49 -0
  47. scope/client/cognition_protocols.py +302 -0
  48. scope/client/constants.py +81 -0
  49. scope/client/dal.py +2382 -0
  50. scope/client/failures.py +70 -0
  51. scope/client/local.py +161 -0
  52. scope/client/mock/__init__.py +7 -0
  53. scope/client/mock/client.py +1034 -0
  54. scope/client/sessions.py +1688 -0
  55. scope/client/spans.py +95 -0
  56. scope/client/utils.py +392 -0
  57. scope/connectors/__init__.py +13 -0
  58. scope/connectors/base.py +52 -0
  59. scope/connectors/clickhouse.py +105 -0
  60. scope/connectors/neo4j.py +220 -0
  61. scope/connectors/sqlalchemy.py +131 -0
  62. scope/core/config.py +530 -0
  63. scope/core/exceptions.py +64 -0
  64. scope/dependencies.py +164 -0
  65. scope/health.py +10 -0
  66. scope/interfaces/__init__.py +33 -0
  67. scope/interfaces/data_provider.py +61 -0
  68. scope/interfaces/integration_example.py +310 -0
  69. scope/interfaces/kg_provider.py +91 -0
  70. scope/interfaces/metrics_provider.py +92 -0
  71. scope/interfaces/models.py +185 -0
  72. scope/models/kg.py +48 -0
  73. scope/models/live_topology.py +78 -0
  74. scope/models/otel_traces.py +1595 -0
  75. scope/providers/__init__.py +277 -0
  76. scope/providers/_graph.py +59 -0
  77. scope/providers/cognition_protocols.py +178 -0
  78. scope/providers/kg.py +702 -0
  79. scope/providers/kg_query_runner.py +109 -0
  80. scope/providers/neo4j_mce.py +18 -0
  81. scope/providers/scope_metrics.py +7 -0
  82. scope/query_builders/__init__.py +14 -0
  83. scope/query_builders/cognition_protocol_graph.py +191 -0
  84. scope/query_builders/concepts.py +112 -0
  85. scope/query_builders/dal.py +931 -0
  86. scope/query_builders/failure_graph.py +102 -0
  87. scope/query_builders/features.py +5 -0
  88. scope/query_builders/kg.py +416 -0
  89. scope/query_builders/labels.py +53 -0
  90. scope/query_builders/live_topology.py +503 -0
  91. scope/query_builders/metric_graph.py +196 -0
  92. scope/query_builders/metrics.py +354 -0
  93. scope/query_builders/semanticgroups.py +46 -0
  94. scope/query_builders/sessions.py +208 -0
  95. scope/query_builders/symbolic.py +615 -0
  96. scope/query_builders/trajectory.py +76 -0
  97. scope/query_builders/types.py +20 -0
  98. scope/query_builders/ui.py +3278 -0
  99. scope/query_builders/waste_estimation.py +221 -0
  100. scope/repositories/__init__.py +28 -0
  101. scope/repositories/clickhouse_otel_repository.py +135 -0
  102. scope/repositories/otel_repository.py +97 -0
  103. scope/repositories/sqlite_repository.py +215 -0
  104. scope/scripts/__init__.py +2 -0
  105. scope/scripts/seed.py +35 -0
  106. scope/workarounds.py +38 -0
@@ -0,0 +1,65 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Shared helpers for endpoint modules."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import TYPE_CHECKING
8
+
9
+ from fastapi import Request
10
+
11
+ from scope.client.base import SCOPEAPIClient
12
+ from scope.connectors.base import Connector as _Connector
13
+ from scope.models.otel_traces import Filters
14
+
15
+ if TYPE_CHECKING:
16
+ from scope.interfaces.metrics_provider import MetricsProvider
17
+
18
+
19
+ def build_filters(request: Request) -> Filters:
20
+ """Parse query-string parameters into a :class:`Filters` instance."""
21
+ params = dict(request.query_params)
22
+ return Filters(**{k: v for k, v in params.items() if k in Filters.model_fields})
23
+
24
+
25
+ # ── Client registry (one LocalClient per connector) ─────────────────────────
26
+
27
+ _clients: dict[int, "SCOPEAPIClient"] = {}
28
+
29
+
30
+ def get_client(
31
+ api_client: _Connector | None = None,
32
+ metrics_provider: MetricsProvider | None = None,
33
+ ) -> SCOPEAPIClient:
34
+ """Return (and lazily create) a :class:`LocalClient` for *api_client*.
35
+
36
+ Each distinct connector instance gets its own ``LocalClient`` so that
37
+ SQL-backed and Neo4j-backed endpoints don't share a single client.
38
+
39
+ Parameters
40
+ ----------
41
+ api_client:
42
+ Database connector. *None* → use the default repository.
43
+ metrics_provider:
44
+ Optional :class:`MetricsProvider` to inject into the client.
45
+ When given, the client delegates metric operations to it.
46
+ """
47
+ key = id(api_client) if api_client is not None else 0
48
+ if key not in _clients:
49
+ from scope.client.local import LocalClient
50
+
51
+ _clients[key] = (
52
+ LocalClient(db=api_client, metrics_provider=metrics_provider)
53
+ if api_client is not None
54
+ else LocalClient(metrics_provider=metrics_provider)
55
+ )
56
+ else:
57
+ # Update provider on an existing client if a new one is supplied
58
+ if metrics_provider is not None:
59
+ _clients[key].metrics_provider = metrics_provider # type: ignore[attr-defined]
60
+ return _clients[key]
61
+
62
+
63
+ def reset_client() -> None:
64
+ """Force re-creation of all shared clients (used by tests)."""
65
+ _clients.clear()
@@ -0,0 +1,195 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """FastAPI router for the /kg (knowledge-graph) endpoint."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+ import redis as redis_lib
10
+ from fastapi import APIRouter, Depends, HTTPException, Request
11
+
12
+ from scope.api.api_v1.endpoints.helpers import get_client
13
+ from scope.cache import cached, make_cache_key
14
+ from scope.connectors.base import Connector
15
+ from scope.core.config import settings
16
+ from scope.core.exceptions import NotFoundError, ValidationError
17
+ from scope.dependencies import get_neo4j_db, get_redis
18
+ from scope.models.kg import (
19
+ NeighborSession,
20
+ NeighborsRequest,
21
+ NeighborsResponse,
22
+ )
23
+ from scope.models.otel_traces import KGQueryRequest, KGQueryResponse
24
+
25
+ router = APIRouter()
26
+
27
+
28
+ def _client(db: Connector = Depends(get_neo4j_db)): # noqa: B008
29
+ """Lazily resolve the KG client from the shared Neo4j dependency."""
30
+ return get_client(api_client=db)
31
+
32
+
33
+ @router.get("/get_state_by_session_id/{session_id}")
34
+ def get_state_by_session_id(
35
+ session_id: str,
36
+ kg_client=Depends(_client), # noqa: B008
37
+ redis_client: redis_lib.Redis = Depends(get_redis), # noqa: B008
38
+ ) -> dict:
39
+ """Return the state associated with a given session ID."""
40
+ key = make_cache_key("kg:state", {"session": session_id})
41
+ return cached(
42
+ redis_client=redis_client,
43
+ key=key,
44
+ fetch=lambda: kg_client.get_state_by_session_id(session_id),
45
+ ttl=settings.CACHE_TTL_SECONDS,
46
+ enabled=settings.CACHE_ENABLED,
47
+ )
48
+
49
+
50
+ @router.post("/neighbors", response_model=NeighborsResponse)
51
+ def get_neighbors(
52
+ body: NeighborsRequest, kg_client=Depends(_client)
53
+ ) -> NeighborsResponse: # noqa: B008
54
+ """Find sessions whose embedding is close to a given session or vector.
55
+
56
+ Provide **either** ``session_id`` (to look up the embedding from the KG)
57
+ **or** ``embedding_vector`` (to query directly with a raw vector).
58
+ """
59
+ # ── validate input ────────────────────────────────────────────────────
60
+ if body.session_id is None and body.embedding_vector is None:
61
+ raise ValidationError(
62
+ "Either 'session_id' or 'embedding_vector' must be provided.",
63
+ )
64
+
65
+ # ── resolve embedding vector ──────────────────────────────────────────
66
+ embedding = body.embedding_vector
67
+ if embedding is None:
68
+ embedding = kg_client.get_embedding_by_session_id(body.session_id)
69
+ if embedding is None:
70
+ raise NotFoundError(
71
+ f"No embedding found for session '{body.session_id}'.",
72
+ )
73
+
74
+ # ── query Neo4j ───────────────────────────────────────────────────────
75
+ rows = kg_client.get_neighbors(
76
+ embedding=embedding,
77
+ max_distance=body.max_distance,
78
+ max_neighbors=body.max_neighbors,
79
+ metric_names=body.metric_names,
80
+ distance_metric=body.distance_metric,
81
+ )
82
+
83
+ # ── build response ────────────────────────────────────────────────────
84
+ neighbors: list[NeighborSession] = []
85
+ for row in rows:
86
+ # Flatten metric nodes [{metricName: ..., metricResult: ...}, ...]
87
+ # into a simple {name: value} dict.
88
+ raw_metrics = row.get("metrics") or []
89
+ metrics_dict = {}
90
+ for m in raw_metrics:
91
+ if not m or "metricName" not in m:
92
+ continue
93
+ value = m.get("metricResult")
94
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
95
+ value = None
96
+ metrics_dict[m["metricName"]] = value
97
+
98
+ neighbors.append(
99
+ NeighborSession(
100
+ session_id=row["sessionId"],
101
+ distance=row["distance"],
102
+ metrics=metrics_dict or None,
103
+ embedding=row.get("embedding"),
104
+ execution_graph=row.get("executionGraph"),
105
+ )
106
+ )
107
+
108
+ return NeighborsResponse(neighbors=neighbors)
109
+
110
+
111
+ @router.get("/info")
112
+ def kg_info(request: Request, kg_client=Depends(_client)) -> Any: # noqa: B008
113
+ """Return descriptive information about this endpoint."""
114
+ return kg_client.info(domain="kg")
115
+
116
+
117
+ # ── Generic KG node query (used by remote SCOPEApiRawProvider) ──────────────
118
+
119
+
120
+ @router.post("/query", response_model=KGQueryResponse)
121
+ def query_kg_nodes(body: KGQueryRequest) -> Any:
122
+ """Execute a parameterized node query against the knowledge graph.
123
+
124
+ Translates the request into a Cypher query identical to
125
+ :meth:`Neo4jRawProvider.query_nodes`. Intended for use by the
126
+ ``SCOPEApiRawProvider`` in ``mce-client`` so that compute workers
127
+ don't need a direct Neo4j connection.
128
+ """
129
+ from scope.dependencies import get_neo4j_db
130
+
131
+ db = next(get_neo4j_db())
132
+
133
+ label_part = (
134
+ f":{body.entity_type}" if body.entity_type and body.entity_type != "*" else ""
135
+ )
136
+ clauses = [f"MATCH (n{label_part})"]
137
+ params: dict = {}
138
+
139
+ where_parts: list[str] = []
140
+ if body.filters:
141
+ for k, v in body.filters.items():
142
+ pk = f"filter_{k}"
143
+ where_parts.append(
144
+ f"n.{k} IN ${pk}" if isinstance(v, list) else f"n.{k} = ${pk}"
145
+ )
146
+ params[pk] = v
147
+ if body.where_clause:
148
+ wc = body.where_clause.strip()
149
+ if not wc.lower().startswith("where"):
150
+ where_parts.append(f"({wc})")
151
+ if where_parts:
152
+ clauses.append("WHERE " + " AND ".join(where_parts))
153
+
154
+ if body.columns and body.columns != ["*"]:
155
+ ret_parts = []
156
+ for col in body.columns:
157
+ if "(" in col or " AS " in col.upper() or "." in col:
158
+ ret_parts.append(col)
159
+ else:
160
+ ret_parts.append(f"n.{col} AS {col}")
161
+ clauses.append("RETURN " + ", ".join(ret_parts))
162
+ else:
163
+ clauses.append("RETURN n")
164
+
165
+ if body.order_by:
166
+ sort_parts = []
167
+ for field in body.order_by:
168
+ direction = "DESC" if field.startswith("-") else "ASC"
169
+ f_clean = field.lstrip("-")
170
+ if "." not in f_clean:
171
+ f_clean = f"n.{f_clean}"
172
+ sort_parts.append(f"{f_clean} {direction}")
173
+ clauses.append("ORDER BY " + ", ".join(sort_parts))
174
+
175
+ if body.limit:
176
+ clauses.append(f"LIMIT {int(body.limit)}")
177
+
178
+ cypher = "\n".join(clauses)
179
+
180
+ try:
181
+ with db.driver.session() as s:
182
+ result = s.run(cypher, **params)
183
+ rows = []
184
+ for record in result:
185
+ row = dict(record)
186
+ if "n" in row and hasattr(row["n"], "items") and len(row) == 1:
187
+ rows.append(dict(row["n"].items()))
188
+ else:
189
+ safe: dict = {}
190
+ for k, v in row.items():
191
+ safe[k] = dict(v.items()) if hasattr(v, "items") else v
192
+ rows.append(safe)
193
+ return KGQueryResponse(results=rows, total=len(rows))
194
+ except Exception as exc:
195
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
@@ -0,0 +1,71 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """FastAPI router for the /labels endpoint.
4
+
5
+ Endpoints
6
+ ---------
7
+ GET /labels/{session_id} — Retrieve the label for a session.
8
+ PUT /labels/{session_id} — Create or update a label for a session.
9
+ DELETE /labels/{session_id} — Remove the label for a session.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ import redis as redis_lib
17
+ from fastapi import APIRouter, Depends
18
+
19
+ from scope.api.api_v1.endpoints.helpers import get_client
20
+ from scope.cache import cached, make_cache_key
21
+ from scope.connectors.base import Connector
22
+ from scope.core.config import settings
23
+ from scope.dependencies import get_db, get_redis
24
+ from scope.models.otel_traces import (
25
+ LabelDeleteResponse,
26
+ LabelPutRequest,
27
+ LabelResponse,
28
+ )
29
+
30
+ router = APIRouter()
31
+
32
+
33
+ def _client(db: Connector = Depends(get_db)): # noqa: B008
34
+ """Lazily resolve the client from the current DB dependency."""
35
+ return get_client(api_client=db)
36
+
37
+
38
+ @router.get("/{session_id}", response_model=LabelResponse)
39
+ def get_label(
40
+ session_id: str,
41
+ client=Depends(_client), # noqa: B008
42
+ redis_client: redis_lib.Redis = Depends(get_redis), # noqa: B008
43
+ ) -> Any:
44
+ """Return the label for *session_id* (or ``null`` if none exists)."""
45
+ key = make_cache_key("labels:session", {"session": session_id})
46
+ return cached(
47
+ redis_client=redis_client,
48
+ key=key,
49
+ fetch=lambda: client.get_label(session_id),
50
+ ttl=settings.CACHE_TTL_SECONDS,
51
+ enabled=settings.CACHE_ENABLED,
52
+ )
53
+
54
+
55
+ @router.put("/{session_id}", response_model=LabelResponse)
56
+ def put_label(
57
+ session_id: str,
58
+ body: LabelPutRequest,
59
+ client=Depends(_client), # noqa: B008
60
+ ) -> Any:
61
+ """Create or update the label for *session_id*."""
62
+ return client.put_label(session_id, body)
63
+
64
+
65
+ @router.delete("/{session_id}", response_model=LabelDeleteResponse)
66
+ def delete_label(
67
+ session_id: str,
68
+ client=Depends(_client), # noqa: B008
69
+ ) -> Any:
70
+ """Delete the label for *session_id*."""
71
+ return client.delete_label(session_id)
@@ -0,0 +1,89 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """FastAPI router for the /live_topology endpoint."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+ from fastapi import APIRouter, Depends
10
+
11
+ from scope.dependencies import ApplicationName
12
+
13
+ from scope.api.api_v1.endpoints.helpers import get_client
14
+ from scope.connectors.base import Connector
15
+ from scope.dependencies import get_db
16
+ from scope.models.live_topology import (
17
+ LiveAgents,
18
+ LiveTopologySessions,
19
+ LiveTools,
20
+ RealtimeTopologyResponse,
21
+ )
22
+
23
+ router = APIRouter()
24
+
25
+
26
+ def _client(db: Connector = Depends(get_db)): # noqa: B008
27
+ """Lazily resolve the live-topology client from the shared database dependency."""
28
+ return get_client(api_client=db)
29
+
30
+
31
+ # ── Endpoints ─────────────────────────────────────────────────────────────────
32
+
33
+
34
+ @router.get(
35
+ "/{application_name}/sessions",
36
+ response_model=LiveTopologySessions,
37
+ )
38
+ def get_live_topology_sessions(
39
+ application_name: ApplicationName,
40
+ lt_client=Depends(_client), # noqa: B008
41
+ ) -> Any:
42
+ """Return live topology sessions for a specific application."""
43
+ return lt_client.get_live_topology_sessions(application_name=application_name)
44
+
45
+
46
+ @router.get(
47
+ "/agents",
48
+ response_model=LiveAgents,
49
+ )
50
+ def get_live_agents(
51
+ lt_client=Depends(_client), # noqa: B008
52
+ ) -> Any:
53
+ """Return live agents"""
54
+ return lt_client.get_live_agents()
55
+
56
+
57
+ @router.get(
58
+ "/tools",
59
+ response_model=LiveTools,
60
+ )
61
+ def get_live_tools(
62
+ lt_client=Depends(_client), # noqa: B008
63
+ ) -> Any:
64
+ """Return live tools"""
65
+ return lt_client.get_live_tools()
66
+
67
+
68
+ @router.get(
69
+ "/sessions/{session_id}/topology",
70
+ response_model=RealtimeTopologyResponse,
71
+ )
72
+ def get_realtime_topology(
73
+ session_id: str,
74
+ lt_client=Depends(_client), # noqa: B008
75
+ ) -> Any:
76
+ """Return a real-time topology graph for a session.
77
+
78
+ Combines the static graph structure (nodes, edges) derived from the most
79
+ recent ``*.graph`` span for the session with live status information sourced
80
+ from ``topology.node.*`` and ``tool.*`` events in ``otel_logs``.
81
+
82
+ Each node carries:
83
+ - ``type``: ``"agent"`` or ``"tool"``
84
+ - ``status``: ``"active"``, ``"completed"``, or ``"unknown"``
85
+ - ``start_time`` / ``end_time``: ISO timestamps from live events
86
+ - ``description``: agent description if available
87
+ - ``data``: tool list for agent nodes that expose tools
88
+ """
89
+ return lt_client.get_realtime_topology(session_id=session_id)