subscribe method

Future<void> subscribe({
  1. required Client client,
  2. required MCPUIRuntime runtime,
  3. required String uri,
  4. String? binding,
  5. String? ownerKey,
})

FR-RES-001~003

Implementation

Future<void> subscribe({
  required Client client,
  required MCPUIRuntime runtime,
  required String uri,
  String? binding,
  String? ownerKey,
}) async {
  _logger.debug('Subscribing resource',
      {'uri': uri, 'binding': binding, 'ownerKey': ownerKey});
  try {
    // Reference-counted: this client may be shared with a composed tile
    // naming the same device. The server knows only "subscribed" or not, so
    // whoever released first used to stop the other's stream.
    await SharedResourceSubscriptions.subscribe(client, uri);
  } catch (e, st) {
    _logger.logError('subscribeResource failed', e, st, {'uri': uri});
    throw ResourceSubscriptionException(uri, cause: e);
  }

  if (ownerKey != null) {
    _active.putIfAbsent(ownerKey, () => <String>{}).add(uri);
  }

  if (binding != null) {
    runtime.registerResourceSubscription(uri, binding);
    _logger.debug('Registered binding', {'uri': uri, 'binding': binding});
  }

  // Initial read (FR-RES-003) — failures are logged but not propagated.
  try {
    final resource = await client.readResource(uri);
    _apply(runtime, binding, resource);
  } catch (e) {
    _logger.warn('Initial resource read failed', {'uri': uri}, e);
  }
}