CREATE TABLE IF NOT EXISTS `mcp_tokens` (
  `id`          int(11) NOT NULL AUTO_INCREMENT,
  `title`       varchar(150) NOT NULL DEFAULT '',
  `prefix`      varchar(16) NOT NULL DEFAULT '',
  `token_hash`  char(64) NOT NULL,
  `enabled`     tinyint(1) NOT NULL DEFAULT 1,
  `created`     datetime DEFAULT NULL,
  `expires`     datetime DEFAULT NULL,
  `last_used`   datetime DEFAULT NULL,
  `user_id`     int(11) NOT NULL,
  `rate_limit`  int(11) NOT NULL DEFAULT 0,
  `comment`     varchar(500) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `token_hash` (`token_hash`),
  KEY `user_id` (`user_id`),
  KEY `prefix` (`prefix`)
);

CREATE TABLE IF NOT EXISTS `mcp_token_scopes` (
  `id`         int(11) NOT NULL AUTO_INCREMENT,
  `token_id`   int(11) NOT NULL,
  `component`  varchar(150) NOT NULL DEFAULT '',
  `tool_name`  varchar(150) NOT NULL DEFAULT '*',
  PRIMARY KEY (`id`),
  UNIQUE KEY `token_tool` (`token_id`,`component`,`tool_name`),
  KEY `token_id` (`token_id`)
);

CREATE TABLE IF NOT EXISTS `mcp_call_log` (
  `id`          int(11) NOT NULL AUTO_INCREMENT,
  `ts`          datetime NOT NULL,
  `token_id`    int(11) DEFAULT NULL,
  `user_id`     int(11) NOT NULL DEFAULT 0,
  `client_ip`   varchar(64) DEFAULT NULL,
  `component`   varchar(150) NOT NULL DEFAULT '',
  `tool_name`   varchar(150) NOT NULL DEFAULT '',
  `contract_id` int(11) NOT NULL DEFAULT 0,
  `duration`    int(11) NOT NULL DEFAULT 0,
  `success`     tinyint(1) NOT NULL DEFAULT 1,
  `denied`      tinyint(1) NOT NULL DEFAULT 0,
  `error_text`  varchar(1000) DEFAULT NULL,
  `args`        mediumtext DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `ts` (`ts`),
  KEY `token_ts` (`token_id`,`ts`),
  KEY `user_ts` (`user_id`,`ts`)
);