hat.event.manager.mcp

  1import functools
  2
  3from hat import aio
  4from hat import juggler
  5from hat.drivers import mcp
  6from hat.drivers import net
  7
  8from hat.event import eventer
  9from hat.event.manager import common
 10from hat.event.manager import rest
 11
 12
 13async def run(addr: net.StreamAddress,
 14              client_name: str,
 15              client_token: str | None,
 16              http_addr: net.TcpAddress):
 17    async_group = aio.Group()
 18
 19    try:
 20        client = await eventer.connect(addr=addr,
 21                                       client_name=client_name,
 22                                       client_token=client_token)
 23        await _bind_resource(async_group, client)
 24
 25        server = await _create_web_server(http_addr=http_addr,
 26                                          client=client)
 27        await _bind_resource(async_group, server)
 28
 29        await async_group.wait_closing()
 30
 31    finally:
 32        await aio.uncancellable(async_group.async_close())
 33
 34
 35async def _create_web_server(http_addr, client):
 36    mcp_server = mcp.Server(
 37        name='hat-event',
 38        instructions="Hat Open Event Server interface for querying events. "
 39                     "Event is a generic data structure used for "
 40                     "communication and storage of relevant changes happening "
 41                     "through time in a Hat system. Each event is immutable "
 42                     "and uniquely identified by its event id. Event "
 43                     "contains: id (unique event identifier), type (list of "
 44                     "strings used as main identifier of event's type), "
 45                     "timestamp (moment when event was registered), source "
 46                     "timestamp (optional time provided by event's source), "
 47                     "payload (optional data with structure defined by "
 48                     "event's type).")
 49
 50    mcp_server.add_tool(
 51        mcp.Tool(
 52            name='query_latest',
 53            title='Query latest events',
 54            description="Return the most recent event for each event type "
 55                        "matching the filters. Events are returned from "
 56                        "latest storage. Use this to read the current "
 57                        "state of something. Results are not paginated. "
 58                        "Omitting event_types returns the latest event of "
 59                        "every type",
 60            input_schema=_query_latest_params_schema,
 61            output_schema=_query_result_schema,
 62            call_cb=functools.partial(_process_query, client,
 63                                      rest.parse_latest_params)))
 64
 65    mcp_server.add_tool(
 66        mcp.Tool(
 67            name='query_timeseries',
 68            title='Query event history',
 69            description="Return historical events from timeseries storage. "
 70                        "Events are filtered by event type and time range, "
 71                        "sorted by registration timestamp or source "
 72                        "timestamp. Paginate with last_event_id while "
 73                        "more_follows is true.",
 74            input_schema=_query_timeseries_params_schema,
 75            output_schema=_query_result_schema,
 76            call_cb=functools.partial(_process_query, client,
 77                                      rest.parse_timeseries_params)))
 78
 79    mcp_server.add_tool(
 80        mcp.Tool(
 81            name='query_server',
 82            title='Query events by originating server',
 83            description="Return all events registered by a specific server in "
 84                        "registration order. Paginate with last_event_id "
 85                        "while more_follows is true",
 86            input_schema=_query_server_params_schema,
 87            output_schema=_query_result_schema,
 88            call_cb=functools.partial(_process_query, client,
 89                                      rest.parse_server_params)))
 90
 91    return await juggler.listen(host=http_addr.host,
 92                                port=http_addr.port,
 93                                ws_path=None,
 94                                index_path=None,
 95                                additional_routes=[mcp_server.route])
 96
 97
 98async def _process_query(client, parse_params, args):
 99    try:
100        params = parse_params(args)
101
102    except Exception as e:
103        raise Exception(f"parse params error: {e}")
104
105    result = await client.query(params)
106
107    return common.query_result_to_json(result)
108
109
110async def _bind_resource(async_group, resource):
111    try:
112        async_group.spawn(aio.call_on_cancel, resource.async_close)
113        async_group.spawn(aio.call_on_done, resource.wait_closing(),
114                          async_group.close)
115
116    except Exception:
117        await aio.uncancellable(resource.async_close())
118        raise
119
120
121_query_event_type_schema = {
122    'title': 'Query event type',
123    'description': "Event type used for event querying. Can contain segments "
124                   "'?' (as any segment) and '*' (only as last segment).",
125    'type': 'array',
126    'items': {
127        'title': 'Query event type segment',
128        'description': "Single query event type segment. '?' matches any "
129                       "single event type segment. '*' matches zero or "
130                       "more arbitrary event type segments.",
131        'type': 'string'}}
132
133_event_type_schema = {
134    'title': 'Event type',
135    'type': 'array',
136    'items': {
137        'title': 'Event type segment',
138        'description': "Single event type segment. Values '*' and '?' are not "
139                       "valid. Character '/' should not be used as part of "
140                       "segment value.",
141        'type': 'string'}}
142
143_timestamp_schema = {
144    'title': 'Timestamp',
145    'description': 'Time elapsed from epoch (1970-01-01T00:00:00Z)',
146    'type': 'object',
147    'required': ['s', 'us'],
148    'properties': {
149        's': {
150            'title': 'Seconds',
151            'description': "Number of seconds from epoch. Can be negative "
152                           "(represent time before epoch).",
153            'type': 'integer'},
154        'us': {
155            'title': 'Microseconds',
156            'description': "Microseconds within the second.",
157            'type': 'integer',
158            'minimum': 0,
159            'maximum': 999999}}}
160
161_event_id_schema = {
162    'title': 'Event identifier',
163    'type': 'object',
164    'required': ['server', 'session', 'instance'],
165    'properties': {
166        'server': {
167            'title': 'Server identifier',
168            'description': 'Identifier of server that created the event.',
169            'type': 'integer'},
170        'session': {
171            'title': 'Session identifier',
172            'description': 'Identifier of session that created the event.',
173            'type': 'integer'},
174        'instance': {
175            'title': 'Instance identifier',
176            'description': 'Identifier of event as part of session.',
177            'type': 'integer'}}}
178
179_payload_schema = {
180    'title': 'Payload',
181    'oneOf': [
182        {'title': 'Binary serialized payload',
183         'type': 'object',
184         'required': ['data_type', 'binary_type', 'data'],
185         'properties': {
186            'data_type': {
187                'const': 'binary'},
188            'binary_type': {
189                'title': 'Binary type identifier',
190                'type': 'string'},
191            'data': {
192                'title': 'Binary data',
193                'description': "Hex encoded bytes.",
194                'type': 'string'}}},
195        {'title': 'JSON serialized payload',
196         'type': 'object',
197         'required': ['data_type', 'data'],
198         'properties': {
199            'data_type': {
200                'const': 'json'},
201            'data': {
202                'title': 'JSON data'}}}]}
203
204_event_schema = {
205    'title': 'Event',
206    'type': 'object',
207    'required': ['id', 'type', 'timestamp', 'source_timestamp', 'payload'],
208    'properties': {
209        'id': _event_id_schema,
210        'type': _event_type_schema,
211        'timestamp': _timestamp_schema,
212        'source_timestamp': {
213            'oneOf': [
214                {'type': 'null'},
215                _timestamp_schema]},
216        'payload': {
217            'oneOf': [
218                {'type': 'null'},
219                _payload_schema]}}}
220
221_query_latest_params_schema = {
222    'title': 'Query latest parameters',
223    'type': 'object',
224    'properties': {
225        'event_types': {
226            'type': 'array',
227            'items': _query_event_type_schema}}}
228
229_query_timeseries_params_schema = {
230    'title': 'Query timeseries parameters',
231    'type': 'object',
232    'properties': {
233        'event_types': {
234            'type': 'array',
235            'items': _query_event_type_schema},
236        't_from': _timestamp_schema,
237        't_to': _timestamp_schema,
238        'source_t_from': _timestamp_schema,
239        'source_t_to': _timestamp_schema,
240        'order': {
241            'enum': ['descending', 'ascending'],
242            'default': 'descending'},
243        'order_by': {
244            'enum': ['timestamp', 'sourceTimestamp'],
245            'default': 'timestamp'},
246        'max_results': {
247            'type': 'integer'},
248        'last_event_id': _event_id_schema}}
249
250_query_server_params_schema = {
251    'title': 'Query server parameters',
252    'type': 'object',
253    'required': ['server_id'],
254    'properties': {
255        'server_id': {
256            'type': 'integer'},
257        'persisted': {
258            'type': 'boolean',
259            'default': False},
260        'max_results': {
261            'type': 'integer'},
262        'last_event_id': _event_id_schema}}
263
264_query_result_schema = {
265    'title': 'Query result',
266    'type': 'object',
267    'required': ['events', 'more_follows'],
268    'properties': {
269        'events': {
270            'type': 'array',
271            'items': _event_schema},
272        'more_follows': {
273            'type': 'boolean'}}}
async def run( addr: hat.drivers.net.stream.TcpAddress | pathlib.Path, client_name: str, client_token: str | None, http_addr: hat.drivers.net.stream.TcpAddress):
14async def run(addr: net.StreamAddress,
15              client_name: str,
16              client_token: str | None,
17              http_addr: net.TcpAddress):
18    async_group = aio.Group()
19
20    try:
21        client = await eventer.connect(addr=addr,
22                                       client_name=client_name,
23                                       client_token=client_token)
24        await _bind_resource(async_group, client)
25
26        server = await _create_web_server(http_addr=http_addr,
27                                          client=client)
28        await _bind_resource(async_group, server)
29
30        await async_group.wait_closing()
31
32    finally:
33        await aio.uncancellable(async_group.async_close())